我有一个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'...
答案 0 :(得分:2)
你可能在gulpfile的顶部附近有这样的东西:
var webpackConfig = require('./webpack.config.js');
这意味着您的webpack配置会在<{strong> _set-env:dev
任务运行之前进行评估。记住:你的gulpfile只定义任务。在评估整个gulpfile之后,任务本身才会运行。
您需要推迟要求您的网络包配置,直到<{>> _set-env:dev
任务运行后,删除gulpfile顶部的行并将require()
直接放入您的watch
任务:
gulp.task("watch", ["_set-env:dev"], function() {
// modify default webpack configuration for Development Server
var webpackDevConfig = Object.create(require('./webpack.config.js'));