Webpack / Express – 服务器找不到的环境variables

在我的Express / React应用程序中,我使用Webpack来处理服务器端的渲染。 但是,我正在遇到与我试图在我的Express服务器脚本中访问的环境variables有关的构build错误。

在服务器脚本index.js ,我设置了一些variables,如下所示:

 const gitCommit = process.env.GIT_COMMIT || require("./gitignore/git_commit.js"), buildDate = process.env.BUILD_DATE || require("./gitignore/build_date.js") 

而且由于我在本地机器上运行testing生产版本,我删除了gitignore/目录并设置了这些环境variables:

 $ export GIT_COMMIT="test commit hash" $ export BUILD_DATE="test build date" 

然后我npm run build ,执行以下脚本:

 "build:client": "webpack --config webpack.config.js", "build:server": "webpack --config webpack.server.config.js", "build": "npm run build:client && npm run build:server" 

build:client执行没有问题,但build:server抛出错误…

 ERROR in ./index.js Module not found: Error: Can't resolve './gitignore/git_commit.js' in '/Users/filepath' @ ./index.js 12:38-74 ERROR in ./index.js Module not found: Error: Can't resolve './gitignore/build_date.js' in '/Users/filepath' @ ./index.js 13:42-78 

这意味着在index.js引用的两个环境variables无法find,所以它正在寻找gitignore/而不是存在(我的意思是,它确实存在本地,但我已经删除,因为我模拟生产构build)。

这里是完整的webpack.server.config.js

 const fs = require("fs"), path = require("path")// , // ExtractTextPlugin = require("extract-text-webpack-plugin") module.exports = { "entry": path.resolve(__dirname, "index.js"), // keep node_module paths out of the bundle "externals": fs.readdirSync(path.resolve(__dirname, "node_modules")).concat(["react-dom/server", "react/addons"]).reduce((ext, mod) => { ext[mod] = `commonjs ${mod}` return ext }, {}), "module": { "loaders": [ { "exclude": /node_modules/, "loader": "babel-loader", "query": { "presets": ["react", "es2015", "stage-2"] }, "test": /\.jsx$/ }, { "exclude": /node_modules/, "loader": "babel-loader", "query": { "presets": ["react", "es2015", "stage-2"] }, "test": /\.js$/ } ] }, "node": { "__dirname": true, "__filename": true }, "output": { "filename": "server.bundle.js" }, "target": "node" } 

现在我期待gitignore/不会被发现,但我不明白的是为什么我设置的两个环境variables没有被index.js检测到 – 他们肯定是在控制台中设置之前,我什至运行build命令。 如果我console.log()他们在webpack.server.config.js开始,它会logging他们正确的,如果我运行我的开发版本,而不是使用服务器configuration),我可以正确地logging他们index.js 。 是什么赋予了?

节点版本6.11.1,NPM版本3.10.10,Webpack版本2.6.0。

您的环境variables只有在运行Webpack时才可用,但在您执行index.js时不可用。 你将需要在你的Webpackconfiguration中使用EnvironmentPlugin :

 plugins: [new webpack.EnvironmentPlugin(['GIT_COMMIT ', 'BUILD_DATE'])] 

那个插件会用它们的实际值replace这些variables。

build议 :不要使用|| 。 Webpack不知道如何优化它。 尝试三元运算符:

 const gitCommit = (process.env.GIT_COMMIT) ? ( process.env.GIT_COMMIT ) : ( require('./gitignore/git_commit.js') ); 

Webpack将把它捆绑到:

 const gitCommit = (true) ? ( "test commit hash" ) : ( require('./gitignore/git_commit.js') ); 

不需要IgnorePlugin 。 更好的是,通过UglifyJSPlugin ,你的代码将被优化为const gitCommit = "test commit hash"; 。 在某些情况下, gitCommit作为variables被完全删除。 它的string值将被用在你应用gitCommit地方。