【问题标题】:Webpack definePlugin not setting/reading node_env variableWebpack definePlugin 没有设置/读取 node_env 变量
【发布时间】:2017-08-22 08:38:04
【问题描述】:

我在通过 Webpack 的 definePlugin 将 node_env var 注入到我的代码中时遇到了真正的问题,并且在阅读了许多帖子之后似乎没有任何效果。我觉得我错过了什么......

所以我的生产 webpack 配置是 -

// Config
import path from 'path';
import webpack from 'webpack';
import config from './config';


/**
 * Webpack config for compiling the
 * React/Redux/ES6 scripts.
 *
 * ENV = production
 *
 * @type {Object}
 */
module.exports = {
    entry: path.resolve(__dirname, '../', config.assets.scripts.src_dir, config.assets.scripts.entry),
    devtool: false,
    output: {
        path: path.resolve(__dirname, config.assets.scripts.dist_dir),
        filename: config.assets.scripts.dist_min
    },
    module: {
        loaders: [
            {
                test: /.js?$/,
                loader: 'babel-loader?presets[]=react,presets[]=es2015,presets[]=stage-0',
                exclude: /node_modules/
            },
            {
                test: /\.json$/,
                loader: 'json-loader'
            }
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('production')
            }
        }),
        new webpack.optimize.UglifyJsPlugin({})
    ]
};

我尝试为 react、react-dom 和 react-redux 设置别名,但绝对无济于事,React 仍然警告我我正在使用 node_env=production 之外的缩小版本(redux 仍然会抛出这个错误)。

仅供参考,我使用的是 webpack 2.2.1 版。

这是否与 babel-loader 以某种方式发生冲突有关?如果有人能指出我正确的方向,那就太好了。

【问题讨论】:

    标签: reactjs webpack react-redux


    【解决方案1】:

    尝试将 DefinePluginNODE_ENV 更改为这个 -

    plugins: [
        new webpack.DefinePlugin({
            'process.env.NODE_ENV' : JSON.stringify('production')
        }),
        new webpack.optimize.UglifyJsPlugin({
            minimize : true,
            compress : {
                warnings : false
            }
        })
    ]
    

    【讨论】:

    • 这确实有效(或者至少我认为它确实有效,因为它似乎已经清除了错误)。您是否知道为什么必须这样指定对象属性?这是 Webpack 的错误吗?谢谢
    • @liamta 我认为您应该阅读此线程github.com/webpack/webpack/issues/868 以获得更多说明,如果它对您有用,那么请接受答案。谢谢
    猜你喜欢
    • 2017-06-02
    • 1970-01-01
    • 2014-11-18
    • 2018-06-01
    • 2020-01-01
    • 2012-02-12
    • 1970-01-01
    • 2020-11-18
    • 2012-05-19
    相关资源
    最近更新 更多