从gulp注入环境变量到webpack

3

我有一个gulpfile,从中我启动webpack打包。webpack配置中定义了一个别名,使用process.env.NODE_ENV如下所示:

.
.
resolve: {
    modulesDirectories: ["node_modules", "js", "jsx"],
    extensions: ["", ".js", ".jsx"],
    alias: {
        config: path.join(__dirname, ('config.' + process.env.NODE_ENV + '.js'))
    }
}..

在 gulpfile 中,我有两个任务按顺序执行。
  1. set-env that sets the environment variable using gulp-env as follows

    gulpEnv({
        vars: {
            NODE_ENV: 'dev'
        }
    });
    
  2. webpack task that depends on the previous task and executes only when the first is completed

看起来变量没有被正确地注入。文件名被解析为config.undefined.js。我做错了什么吗?


你找到解决方法了吗?我也有完全相同的问题。 - Fernando
1个回答

1
I changed my approach it to something like this 我改变了我的方法,变成了这样
Webpack Webpack
var NODE_ENV = process.env.NODE_ENV;

var config = {
    .
    .
    resolve: {
        modulesDirectories: ["node_modules", "js", "jsx"],
        extensions: ["", ".js", ".jsx"],
        alias: {
            //<envt> will be injected by gulp
            config: config: path.join(__dirname, ('config.<envt>.js'))
        }
    }
    .
    .
    .
}

//If webpack is directly invoked with NODE_ENV, replacement will happen here
if (NODE_ENV) {
    config['resolve']['alias']['config'] = config['resolve']['alias']['config'].replace(/<envt>/, NODE_ENV);
}

module.exports = config;

Gulp

  1. set-env 中,与其使用 gulp-env,我简单地设置了一个全局变量 NODE_ENV='dev'
  2. webpack 任务中,我执行了 webpackConfig['resolve']['alias']['config'] = webpackConfig['resolve']['alias']['config'].replace(/<envt>/, NODE_ENV);

这对我起作用了


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接