Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack: How can we *conditionally* use a plugin?

In Webpack, I have the following plugins:

plugins: [         new ExtractTextPlugin('styles.css'),         new webpack.optimize.UglifyJsPlugin({             compress: {                 warnings: false             },             drop_console: true,         }),     ] 

I would like to apply the UglifyJsPlugin only for a specific target, so I tried using my intended conditional:

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

However, this fails, showing the following error message:

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

Note that the above code is similar to having false at the end of the plugins array (which emits the same error):

plugins: [         new ExtractTextPlugin('styles.css'),         false     ] 

So, the question is: Is there a way to have conditional plugins on Webpack? (other than using variables?)

like image 646
user2078023 Avatar asked Mar 24 '16 16:03

user2078023


People also ask

What is the use of plugins in webpack?

A webpack plugin is a JavaScript object that has an apply method. This apply method is called by the webpack compiler, giving access to the entire compilation lifecycle.

What is the difference between plugin and loader in webpack?

Loaders work at the individual file level during or before the bundle is generated. Plugins: Plugins work at bundle or chunk level and usually work at the end of the bundle generation process.

What is webpack DefinePlugin?

Oct 29, 2021. Webpack's DefinePlugin() function lets you replace a given token in the compiled code with another token. A common use case is using it to define environment variables when you cannot use an . env file directly.


1 Answers

You can use this syntax which uses the spread operator

plugins: [     new MiniCssExtractPlugin({         filename: '[name].css'     }),     ...(prod ? [] : [new BundleAnalyzerPlugin()]), ], 
like image 80
unloco Avatar answered Oct 08 '22 12:10

unloco