Webpack - 无法设置全局变量,除非设置为' process.env'

时间:2017-12-16 02:38:11

标签: reactjs webpack

我正在使用Webpack版本3.6.0运行React应用程序,并且我在使用DefinePlugin设置全局变量时遇到问题 - 通常设置的值'&#39 ;,因为documentation在整个应用程序中都不可用...但是,如果我将值包装在名为process.env的对象中,则变量在整个应用程序中都可用,尽管前缀为{{1 }}

例如,我希望process.env看起来像这样:

DefinePlugin

这不起作用 - 尝试plugins: [ new Webpack.DefinePlugin({ "NODE_ENV": process.env.NODE_ENV ? JSON.stringify(process.env.NODE_ENV) : JSON.stringify("development"), "SIGNUP_PATH": JSON.stringify("signup") }) ] console.log(NODE_ENV)什么都不做,变量是console.log(SIGNUP_PATH)

令人惊讶的是(或许没有,也许不是,我只是不知道),这有效:

undefined

我可以使用plugins: [ new Webpack.DefinePlugin({ "process.env": { "NODE_ENV": process.env.NODE_ENV ? JSON.stringify(process.env.NODE_ENV) : JSON.stringify("development"), "SIGNUP_PATH": JSON.stringify("signup") } }) ] console.log(process.env.NODE_ENV)等访问变量

为什么我必须将所有内容放入一个名为console.log(process.env.SIGNUP_PATH)的对象中,以便像访问全局一样访问它?我在这里做错了什么,或者只是我不明白这件事?

3 个答案:

答案 0 :(得分:1)

这是一个工作示例。任何地方在我的代码中,我可以引用__ API_URL __

require('dotenv').config({ path: `${__dirname}/src/.dev.env` });
const production = process.env.NODE_ENV === 'production';

const { DefinePlugin, EnvironmentPlugin } = require('webpack');
const HtmlPlugin = require('html-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');
const UglifyPlugin = require('uglifyjs-webpack-plugin');
const ExtractPlugin = require('extract-text-webpack-plugin');

let plugins = [
  new EnvironmentPlugin(['NODE_ENV']),
  new ExtractPlugin('bundle-[hash].css'),
  new HtmlPlugin({ template: `${__dirname}/src/index.html` }),
  new DefinePlugin({
    __DEBUG__: JSON.stringify(!production),
    __API_URL__: JSON.stringify(process.env.API_URL),
    __GOOGLE_CLIENT_ID__: JSON.stringify(process.env.GOOGLE_CLIENT_ID),
    __AWS_ACCESS_KEY_ID__: JSON.stringify(process.env.AWS_ACCESS_KEY_ID),
    __AWS_SECRET_ACCESS_KEY__: JSON.stringify(process.env.AWS_SECRET_ACCESS_KEY),
  }),
];

答案 1 :(得分:0)

忽略引号。 “NODE_ENV”应为NODE_ENV

答案 2 :(得分:0)

最终,此问题是由于我构建了自己的应用程序以利用服务器端渲染而产生的-它需要两个单独的Webpack配置,但最初我只在客户端上包含DefinePlugin设置。基本上,我将DefinePlugin的所有内容放入一个单独的文件中,将其导入到客户端和服务器配置中,然后将其捆绑到最终的webpack.config.prod.js中进行生产(或类似的webpack.config.dev.js用于开发...仅下面显示的生产)。这是所有内容的组合方式:

webpack_config.define-plugin-config.js

module.exports = {
    "API_URL": process.env.API_URL ? JSON.stringify(process.env.API_URL) : JSON.stringify("http://localhost:4000/api/v1/"),
    "SOME_OTHER_VAR": JSON.stringify("foo")
}

webpack.config.server.js

const Webpack = require("webpack"),
    path = require("path"),
    definePluginConfig = require("./webpack_config/define-plugin-config"),
    rule_js = require("./webpack_config/rule"),
    resolve = require("./webpack_config/resolve")

module.exports = {
    "entry": {
        "component": path.join(__dirname, "js/containers/index.jsx")
    },
    "output": {
        "path": path.join(__dirname, "../priv/static/server/js"),
        "filename": "app.js",
        "library": "dl",
        "libraryTarget": "commonjs2"
    },
    "module": {
        "rules": [
            rule_js
        ]
    },
    "resolve": resolve,
    "plugins": [
        new Webpack.DefinePlugin(definePluginConfig)
    ]
}

webpack.config.client.js

const Webpack = require("webpack"),
    ExtractTextPlugin = require("extract-text-webpack-plugin"),
    CopyPlugin = require("copy-webpack-plugin"),
    path = require("path"),
    definePluginConfig = require("./webpack_config/define-plugin-config"),
    rule_js = require("./webpack_config/rule"),
    resolve = require("./webpack_config/resolve")

module.exports = {
    "entry": [
        path.join(__dirname, "js/index.jsx"),
        path.join(__dirname, "styles/index.scss")
    ],
    "output": {
        "path": path.join(__dirname, "../priv/static"),
        "filename": "js/app.js",
        "publicPath": "/"
    },
    "module": {
        "rules": [
            rule_js,
            {
                "test": /\.scss$/,
                "use": ExtractTextPlugin.extract({
                    "fallback": "style-loader",
                    "use": ["css-loader", "sass-loader"]
                })
            },
            {
                "test": /\.css$/,
                "use": ExtractTextPlugin.extract({
                    "fallback": "style-loader",
                    "use": ["css-loader?modules&importLoaders=1&localIdentName=[local]"]
                })
            }
        ]
    },
    "resolve": resolve,
    "plugins": [
        new Webpack.DefinePlugin(definePluginConfig),
        new ExtractTextPlugin({
            "filename": "css/app.css",
            "allChunks": true
        }),
        new CopyPlugin([{ "from": path.join(__dirname, "static") }])
    ]
}

webpack.config.prod.js

const clientWebPackConfig = require("./webpack.config.client"),
    serverWebPackConfig = require("./webpack.config.server"),
    UglifyJsPlugin = require("uglifyjs-webpack-plugin"),
    webpackConfig = [clientWebPackConfig, serverWebPackConfig],
    uglifyJsPluginOptions = { "sourceMap": true }

webpackConfig[0].plugins = [...webpackConfig[0].plugins, new UglifyJsPlugin(uglifyJsPluginOptions)]

module.exports = webpackConfig