Webpack DefinePlugin不会将环境variables传递给节点服务器

Webpack的DefinePlugin不通过环境variables。 我正在使用Webpack v2.2.1

我的Webpack plugins块如下:

 plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify("development"), 'process.env.API_URL': JSON.stringify("test") }), new webpack.optimize.OccurrenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin() ] 

server.js:

 console.log('env', process.env.NODE_ENV) // undefined console.log('url', process.env.API_URL); // undefined 

.babelrcconfiguration:

 {"presets": ["es2015", "stage-0", "react"]} 

我已经调整了babel预设,将Webpack恢复为2.0.0,并且确实没有看到可能导致这些variables不被复制的原因。 如果我需要提供任何额外的信息或代码,lmk。 🙂

希望这对那里的人仍然有帮助。

Webpack创build静态包文件,所以在webpack做这件事情时,环境variables必须是可用的。

基于.babelrc文件,我可以看到它是与webpack捆绑在一起的反应应用程序。 所以你想要做的是安装dotenv作为依赖项npm install --save dotenv

在您的webpack.config.js文件中,您需要执行以下操作:

  //require dotenv and optionally pass path/to/.env const DotEnv = require('dotenv').config({path: __dirname + '/.env'}), webpack = require('webpack'), //Then define a new webpack plugin which reads the .env variables at bundle time dotEnv = new webpack.DefinePlugin({ "process.env": { 'BASE_URL': JSON.stringify(process.env.BASE_URL), 'PORT': JSON.stringify(process.env.PORT) } }); // Then add the newly defined plugin into the plugin section of the exported //config object const config = { entry: `${SRC_DIR}/path/to/index.js`, output: { path: `${DIST_DIR}/app`, filename: 'bundle.js', publicPath: '/app/' }, module: { loaders: [ { test: /\.js?$/, include: SRC_DIR, loader: "babel-loader", exclude: /node_modules/, query: { presets: ["react", "es2015", "stage-3"] } } ] }, plugins: [ dotEnv ] }; module.exports = config; 

所以会发生什么?在捆绑时间,环境variables被全局存储到在新定义的webpack插件中创build的process.env对象中,这使得我们的variables可以通过process.env.[VARIABLE_NAME]

PS:在像heroku这样的云服务器上,确保在部署代码之前设置所有需要的环境variables。 如果在部署代码后进行更改,则需要重新部署webpack以更新存储的variables。 这种方法适用于反应和angular度。 我相信它应该适用于所有的webpack构build。 编辑:另外,我们必须对传入webpack插件的环境variables做一个JSON.stringify()