我有一个gulpfile,在其中创建了webpackDevServer来实时更新我的js代码。我在gulpfile中设置了一个process.env.NODE_ENV
变量,但是由于某种原因,webpack看不到它-它是未定义的。
这是我的gulpfile.js
的相关部分:
gulp.task("watch", ["_set-env:dev"], function() {
// modify default webpack configuration for Development Server
var webpackDevConfig = Object.create(webpackConfig);
webpackDevConfig.devtool = "eval";
webpackDevConfig.debug = "true";
new webpackDevServer(webpack(webpackDevConfig), {
proxy: {
"/api/*": {target: "http://localhost:8000", secure: false},
"/static/*": {target: "http://localhost:8000", secure: false},
"/media/*": {target: "http://localhost:8000", secure: false}
}
}).listen(8001, "localhost", function (err) {
if (err) throw new gutil.PluginError("webpack-dev-server", err);
gutil.log("[webpack-dev-server]", "http://localhost:8001" + webpackDevConfig.output.publicPath);
});
});
gulp.task("_set-env:dev", function() {
gutil.log("set-env", "ENV => development");
genv({
vars: {
NODE_ENV: "development"
}
});
});
然后在webpack中,我检查它的值,并且它是未定义的:
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
...
const environmentsFile = path.join(__dirname, "/environments.json");
const nodeModulesPath = path.join(__dirname, "/node_modules");
const bowerComponentsPath = path.join(__dirname, "/bower_components");
console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
console.log(process.env.NODE_ENV);
const webpackConfig = {
entry: {
app: ["app.js"]
},
在控制台上,我看到:
$ gulp watch
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
undefined
[22:28:34] Using gulpfile ~/Documents/frontend/gulpfile.js
[22:28:34] Starting '_set-env:dev'...
[22:28:34] set-env ENV => development
[22:28:34] Finished '_set-env:dev' after 7.63 ms
[22:28:34] Starting 'watch'...
最佳答案
您可能在gulpfile的顶部附近有这样的内容:
var webpackConfig = require('./webpack.config.js');
这意味着您的Webpack配置将在
_set-env:dev
任务运行之前进行评估。请记住:您的gulpfile仅定义任务。直到评估完整个gulpfile后,任务本身才运行。您需要通过在gulpfile顶部删除行并将
_set-env:dev
直接放入您的require()
任务中,直到执行watch
任务后才需要进行webpack配置:gulp.task("watch", ["_set-env:dev"], function() {
// modify default webpack configuration for Development Server
var webpackDevConfig = Object.create(require('./webpack.config.js'));
关于node.js - 如何将Gulp的process.env.NODE_ENV传递给Webpack?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39882186/