美文网首页
React | 修改React脚手架的默认端口号?

React | 修改React脚手架的默认端口号?

作者: 夏海峰 | 来源:发表于2019-03-05 21:04 被阅读9次

使用 create-react-app 创建的脚手架项目,默认运行端口号是 3000,那我们该怎么修改这个默认的端口号呢?

// 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"
  ]
}

从项目的 package.json 文件中可以看到,npm startreact-scripts start,它使用了 react-script 模块来启动项目。因此我们找到 /node_modules/react-scripts/scripts/start.js ,部分代码如下:

// ......

// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
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('http://bit.ly/CRA-advanced-config')}`
  );
  console.log();
}

// ......

找到 DEFAULT_PORT 变量,修改它的默认值为 3333 即可。

// const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3333;

保存 /node_modules/react-scripts/scripts/start.js 后,再执行npm start,即可看到项目在 3333 端口上运行了。大功告成!


END 2019-03-05

相关文章

网友评论

      本文标题:React | 修改React脚手架的默认端口号?

      本文链接:https://www.haomeiwen.com/subject/bveouqtx.html