Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webpack配置Node环境变量 #138

Open
TieMuZhen opened this issue Mar 19, 2022 · 0 comments
Open

Webpack配置Node环境变量 #138

TieMuZhen opened this issue Mar 19, 2022 · 0 comments
Labels

Comments

@TieMuZhen
Copy link
Owner

在实际项目开发中,需要基于多种环境去设置不同的环境变量以便于在构建阶段或是运行阶段去使用,例如常见的通过process.env.NODE_ENV在构建时去判断当前的构建环境是development还是production,例如需要在开发环境、测试环境和生产环境去访问不同的接口服务器。

Node环境变量

Node环境变量就是指process.env这个属性

process.env 是什么?

它是Nodejs应用程序中,process.env属性,返回包含用户环境的对象,所以它不可以在客户端侧代码中使用,也就不能在浏览器环境上使用。

修改Node环境变量

使用cross-env依赖包,修改package.json文件,支持跨平台配置环境变量。

// package.json
{
  ...,
  "scripts": {
    "start": "npm run dev",
    "dev": "cross-env NODE_ENV=development AAA=123 webpack serve --config ./config/webpack.config.js",
    "build:test": "cross-env NODE_ENV=test  webpack --config ./config/webpack.config.js",
    "build:pro": "cross-env NODE_ENV=production  webpack --config ./config/webpack.config.js"
  },
  ...
}

通过在package.json脚本中设置变量的方式来注入环境变量,同时cross-env还支持去设置多个环境变量,只需要通过空格区分,例如在dev脚本中设置的NODE_ENV=developmentAAA=123

这样在执行npm start就能够通过process.env获取到对应的环境变量。

// webpack.config.js
console.log("【process.env】", process.env.AAA); 

能够在构建时的终端中打印出

【process.env】123

参考文献

@TieMuZhen TieMuZhen added the node label Mar 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant