Mode
webpack 的 mode 設定值有 none、development、production(預設值),
各值的作用如下表
Option | Description |
---|---|
development |
Sets optimization.minimize : false.
Enables |
production |
Sets optimization.minimize : true.
Enables |
none |
Sets optimization.minimize : false. Opts out of any default optimization options |
來實際看各模式對一個範例會有什麼影響
一個範例資料結構如下圖
webpack.config.js 內容為
const path = require('path'); module.exports = { entry: './src/index.js', output: { filename: 'index.js', path: path.resolve(__dirname, 'dist') } };
./src/index.js 內容為
var Hello = "Hello"; var Webpack = "Webpack"; for (let index = 0; index < 3; index++) { console.log(Hello + Webpack); }
index.html 內容為
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="index.js"></script> </head> <body> </body> </html>
打 webpack --mode=production 指令
如發生錯誤,請改嘗試執行下列指令
$ npm install webpack --save-dev
$ npm install webpack-cli --save-dev
$ npx webpack --mode=production
後,經由 chrome 瀏覽器開發工具用 pretty print 查看 ./dist/index.js 內容如下
打 webpack --mode=development 指令後,./dist/index.js 內容為
打 webpack --mode=none 指令後,./dist/index.js 內容為
想要對這三種模式都能做一些客製化時,webpack.config.js 可以改成下面範例結構
const path = require('path'); var config = { entry: { Index: './src/Index.js', }, output: { filename: 'index.js', path: path.resolve(__dirname, 'dist'), }, }; module.exports = (env, argv) => { if (argv.mode === 'development') { /**write your custom code below */ // config.plugins = []; // config.optimization.minimize = false; // config.devtool = "source-map"; // config.module.rules[1].use[0].options = { sourceMap: true }; } if (argv.mode === 'production') { /**write your custom code below */ } if (argv.mode === 'none') { /**write your custom code below */ // config.plugins = []; // config.module.rules[1].use[0].options = { sourceMap: true }; } return config; };
參考資料: