【发布时间】:2017-09-10 15:37:17
【问题描述】:
在我的 Express/React 应用程序中,我使用 Webpack 来处理服务器端渲染。但是,我遇到了与我试图在我的 Express 服务器脚本中访问的环境变量相关的构建错误。
在服务器脚本index.js 中,我设置了一些变量,如下所示:
const gitCommit = process.env.GIT_COMMIT || require("./gitignore/git_commit.js"),
buildDate = process.env.BUILD_DATE || require("./gitignore/build_date.js")
由于我在本地机器上运行测试生产版本,我删除了gitignore/ 目录并设置了这些环境变量:
$ 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 中引用的两个环境变量无法找到,因此它正在寻找不应该存在的gitignore/(我的意思是,它确实存在于本地,但我已经删除了因为我正在模拟生产构建)。
这是完整的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/,但我不明白为什么index.js 没有检测到我设置的两个环境变量 - 它们肯定是在我之前在控制台中设置的运行build 命令。如果我在webpack.server.config.js 的开头console.log() 它们,它会正确记录它们,如果我运行我的开发版本(不使用服务器配置),我可以在index.js 中正确记录它们。什么给了?
Node 版本 6.11.1,NPM 版本 3.10.10,Webpack 版本 2.6.0。
【问题讨论】: