node.js - Webpack/Express - 服务器找不到环境变量

标签 node.js express webpack

在我的 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。

最佳答案

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

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 的任何地方使用。

关于node.js - Webpack/Express - 服务器找不到环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46121561/

相关文章:

javascript - 包含外部 JS 文件的 NodeJS Express sendFile

node.js - Angular CLI-ng服务- Node 进程的cpu使用率高

javascript - 带有 NestJS + Typescript + Webpack + node_modules 的单个文件包

node.js - 使用 AES 256 CTR 在 Node JS 中加密并在 Golang 中解密

ruby-on-rails - rails 和 nodejs 之间的安全性

javascript - Nginx 反向代理到 Node.js 并重写

angularjs - 带有后端 api 的 webpack-dev-server

node.js - 如何使用 mongodb、node.js、express 和 EJS 创建动态站点地图?

javascript - 如果错误回调不执行以下代码

node.js - Express TypeScript 路由属性