Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Webpack:我们如何*有条件地*使用插件?_Javascript_Webpack - Fatal编程技术网

Javascript Webpack:我们如何*有条件地*使用插件?

Javascript Webpack:我们如何*有条件地*使用插件?,javascript,webpack,Javascript,Webpack,在Webpack中,我有以下插件: plugins: [ new ExtractTextPlugin('styles.css'), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, drop_console: true, }), ] 我只想将Ugli

在Webpack中,我有以下插件:

plugins: [
        new ExtractTextPlugin('styles.css'),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            drop_console: true,
        }),
    ]
我只想将
UglifyJsPlugin
应用于特定目标,因此我尝试使用我预期的条件:

plugins: [
        new ExtractTextPlugin('styles.css'),
        (TARGET === 'build') && new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            drop_console: true,
        }),
    ]
但是,此操作失败,显示以下错误消息:

E:\myProject\node_modules\tapable\lib\Tapable.js:164
            arguments[i].apply(this);
                         ^

TypeError: arguments[i].apply is not a function
注意,上面的代码类似于在
插件
数组的末尾有
false
(发出相同的错误):

因此,问题是:
有没有办法在Webpack上安装有条件的插件?(除了使用变量之外?

我认为最干净的方法是设置多个构建。如果您的
webpack.config.js
导出一个配置对象数组,而不是单个对象,那么webpack将自动为每个对象进行构建。我有几个不同的构建,因此我将配置中的共享配置定义为变量,循环不同构建之间的不同因素,并在循环中使用条件检查它是哪个构建。例如:

let allConfigs = [];
let buildTypes = ['dev', 'optimized'];
buildTypes.forEach( (type) => {
  let buildConfig = {};
  // ... other config
  buildConfig.plugins = [];
  if (type === 'optimized') {
    // add Uglify to plugins array
  }
  // ...other config
  allConfigs.push(buildConfig);
});
如果没有变量,它将如下所示:

    plugins: [
        new ExtractTextPlugin('styles.css'),
        (TARGET === 'build') && new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            drop_console: true,
        }),
    ].filter(function(plugin) { return plugin !== false; })

您可以在另一个Web包配置的基础上构建一个Web包配置,并在后一个Web包配置中添加一些插件(和/或更改输出名称等):

这个webpack.release.config.js使用了webpack.config(开发版本),但使用了更多插件

process.env.NODE_ENV = 'release';

const config = require('./webpack.config'),
    webpack = require('webpack');

config.output.filename = 'app.min.js';
// use another plugin, compare to the basic version ←←←
config.plugins.push(new webpack.optimize.UglifyJsPlugin({
    minimize: true
}));

module.exports = config;

同样是一个完整的例子。

我在
webpack.config.js

const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: {
        ...
    },
    output: {
        ...
    },
    module: {
        rules: [
            ...
        ]
    },
    plugins: [
        new ExtractTextPlugin('styles.css'),
    ]
};


if (TARGET === 'build') {
    module.exports.plugins.push(
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            drop_console: true,
        }),
    );
}

您可以使用以下语法:

您可以使用webpack中的参数将
开发
/
生产
值传递给webpack配置,然后有条件地加载插件

NPM脚本:

"start": "webpack --watch --mode=development",
"build": "webpack --mode=production",
webpack.config.js:

module.exports = (env, argv) => {
  console.log("mode: ", argv.mode);

  const isDev = argv.mode === "development";

  const pluginsArr = [new CleanWebpackPlugin()];

  // load plugin only in development mode
  if (isDev) {
    pluginsArr.push(new ExtensionReloader({}));
  }
  return {
    entry: {},
    devtool: isDev ? "inline-source-map" : "", // generate source code only in development mode

    plugins: pluginsArr,
    output: {},
  };
};
您可以使用(noop表示无操作):

或更好/推荐的解决方案,无需额外模块:

const isProd = process.env.NODE_ENV === 'production';
// ...
plugins: [
    isProd ? new Plugin() : false,
].filter(Boolean)
// filter(Boolean) removes items from plugins array which evaluate to
// false (so you can use e.g. 0 instead of false: `new Plugin() : 0`)

您也可以这样做:
[].filter(Boolean)
(请参阅)。使用BundleAnalyzerPlugin,您可以有条件地将
analyzerMode
设置为
disabled
,即
新建BundleAnalyzerPlugin({analyzerMode:process.env.BUNDLE\u ANALYZE?'server':'disabled')应该是可接受的答案。
module.exports = (env, argv) => {
  console.log("mode: ", argv.mode);

  const isDev = argv.mode === "development";

  const pluginsArr = [new CleanWebpackPlugin()];

  // load plugin only in development mode
  if (isDev) {
    pluginsArr.push(new ExtensionReloader({}));
  }
  return {
    entry: {},
    devtool: isDev ? "inline-source-map" : "", // generate source code only in development mode

    plugins: pluginsArr,
    output: {},
  };
};
const isProd = process.env.NODE_ENV === 'production';
const noop = require('noop-webpack-plugin');
// ...
plugins: [
    isProd ? new Plugin() : noop(),
]
const isProd = process.env.NODE_ENV === 'production';
// ...
plugins: [
    isProd ? new Plugin() : false,
].filter(Boolean)
// filter(Boolean) removes items from plugins array which evaluate to
// false (so you can use e.g. 0 instead of false: `new Plugin() : 0`)
plugins: [
    new ExtractTextPlugin('styles.css'),
    (TARGET === 'build') && new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        },
        drop_console: true,
    }),
].filter(Boolean)