【问题标题】:Webpack/Express - environment variables not found by serverWebpack/Express - 服务器找不到环境变量
【发布时间】: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。

【问题讨论】:

    标签: node.js express webpack


    【解决方案1】:

    您的环境变量仅在 Webpack 运行时可用,但在您执行 index.js 时不可用。 你需要像这样在你的 Webpack 配置中使用EnvironmentPlugin

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

    该插件将用变量的实际值替换变量。

    提示:不要使用||。 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 作为变量被完全删除。它的字符串值将用于您应用gitCommit 的任何地方。

    【讨论】:

    • 其实,很抱歉,这不起作用...我将"plugins": [new webpack.EnvironmentPlugin(["GIT_COMMIT", "BUILD_DATE"])] 添加到webpack.server.config.js,但我仍然遇到同样的问题。
    • 我希望您做两件事: 1. 调试您的server.bundle.js process.env 到底发生了什么? EnvironmentPlugin 是否真的替换了这些值? 2. 使用命令行中设置的环境变量运行server.bundle.js,看看会发生什么。
    • 好的,这很有趣——我在命令行上设置了环境变量——对于 GIT_COMMIT,我使用了“TEST GIT COMMIT HASH”。在我的server.bundle.js 中,我得到了:gitCommit = "TEST GIT COMMIT HASH" || __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"./gitignore/git_commit.js\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()))。所以它正确地替换了它......但是为什么webpackMissingModule()
    • 哦,我想我明白了!我在插件中添加了new webpack.IgnorePlugin(/gitignore/),它似乎奏效了!我的server.bundle.js 中仍然有相同的webpackMissingModule() 内容,但它不会引发错误。这是一个好的解决方案,还是枪击时的创可贴?
    • 如果好,请添加到您的答案中,我一定会接受!
    猜你喜欢
    • 1970-01-01
    • 2011-06-21
    • 2017-06-21
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    相关资源
    最近更新 更多