react脚手架生成的项目更换默认端口

1.create-react-app 创建的脚手架项目,默认运行端口号是 3000,有的时候我们需要更改一下端口号,这时候应该怎么做呢?

2.这是 package.json 的文件,它的启动命令是 npm start ,运行的是 react-scripts start,它使用了 react-script 模块来启动项目,因此我们可以找到这个 start.js 的这个文件,即是 /node_modules/react-scripts/scripts/start.js

// package.json
{
  "name": "my-react-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.8.3",
    "react-dom": "^16.8.3",
    "react-scripts": "2.1.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

3.然后就是找到文件夹,node_modules/react-scripts/scripts/start.js 文件的部分代码,然后更改端口号就行了

// Tools like Cloud9 rely on this.
//把这个端口改成自己想要的端口就行,然后重新运行命令运行
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 4000;
const HOST = process.env.HOST || '0.0.0.0';

if (process.env.HOST) {
  console.log(
    chalk.cyan(
      `Attempting to bind to HOST environment variable: ${chalk.yellow(
        chalk.bold(process.env.HOST)
      )}`
    )
  );
  console.log(
    `If this was unintentional, check that you haven't mistakenly set it in your shell.`);
  console.log(
    `Learn more here: ${chalk.yellow('https://bit.ly/CRA-advanced-config')}`
  );
  console.log();

你可能感兴趣的:(react脚手架生成的项目更换默认端口)