Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current `--mode` in webpack.config.js

How can I get the current --mode specified in package.json inside webpack.config.js? (For instance, for pushing some plugins.)

package.json  "scripts": {   "dev": "webpack --mode development",   "build": "webpack --mode production" } 

What I did in Webpack 3:

package.json  "scripts": {     "build": "cross-env NODE_ENV=development webpack",     "prod": "cross-env NODE_ENV=production webpack"   }, 

Then, I was able to get environment in Webpack with process.env.NODE_ENV.

Of course, I can pass NODE_ENV with --mode but I prefer to avoid duplication.

like image 794
xAoc Avatar asked Mar 14 '18 10:03

xAoc


People also ask

What is mode in webpack?

Providing the mode configuration option tells webpack to use its built-in optimizations accordingly.

How do you set mode on webpack?

Set 'mode' option to 'development' or 'production' to enable defaults for this environment. We can get around this by passing --mode production in the cmdline like below: npm run webpack --mode development ... As is mentioned on the webpack documentation, blog and everywhere else on the internet.

Where I can find webpack config js?

The easiest way to get your webpack. config. js file to work is to place it at the top level of your project's folder structure along with your package. json file.

How do I watch Webpacks?

Other Ways to Enable Watch Mode You can also enable watch mode from your Webpack config file: module. exports = { mode: 'development', watch: true, // Enable watch mode entry: { app: `${__dirname}/app. js` }, target: 'web', output: { path: `${__dirname}/bin`, filename: '[name].


1 Answers

You want to avoid duplication of options passed on the script.

When you export a function, the function will be invoked with 2 arguments: an environment env as the first parameter and an options map argv as the second parameter.

package.json

"scripts": {   "build-dev": "webpack --mode development",   "build-prod": "webpack --mode production" }, 

webpack.config.js

module.exports = (env, argv) => {     console.log(`This is the Webpack 4 'mode': ${argv.mode}`);     return {         ...     }; } 

These are the results:

For npm run build-dev:

> webpack --mode development  This is the Webpack 4 'mode': development Hash: 554dd20dff08600ad09b Version: webpack 4.1.1 Time: 42ms Built at: 2018-3-14 11:27:35 

For npm run build-prod:

> webpack --mode production  This is the Webpack 4 'mode': production Hash: 8cc6c4e6b736eaa4183e Version: webpack 4.1.1 Time: 42ms Built at: 2018-3-14 11:28:32 
like image 141
Fernando Espinosa Avatar answered Sep 19 '22 09:09

Fernando Espinosa