webpack4.29.x成神之路(三) 基本配置与mode

 阅读约 7 分钟

目录
上一节:起步

上一节的目录结构如下:

clipboard.png

一、创建配置文件

首先在根目录下新建配置文件webpack.config.js, 并添加如下内容:

webpack.config.js:

module.exports = {
  mode: 'production',
  entry: './src/index.js',
  output: {
    filename: 'main.js'
  }
};

在配置文件中,指定了最基础的三个选项,也是webpack默认的几个配置项,即:

  • 打包环境:mode,
  • 入口:entry
  • 出口:output

此时在根目录下执行:npm run build
将会得到与上节一样的结果。

二、mode选项

在webpack4中如果不指定mode选项,webpack会默认将mode设为 'production',并在打包时发出警告。
mode可选值有三个:'development', 'production', 'none'.

不同模式下,webpack会选择不同的默认打包配置,比如在production模式下,打包会自动对代码进行压缩和各种优化。
三种模式的默认配置如下:

mode: 'development'

// webpack.development.config.js
module.exports = {
+ mode: 'development'
- devtool: 'eval',
- cache: true,
- performance: {
-   hints: false
- },
- output: {
-   pathinfo: true
- },
- optimization: {
-   namedModules: true,
-   namedChunks: true,
-   nodeEnv: 'development',
-   flagIncludedChunks: false,
-   occurrenceOrder: false,
-   sideEffects: false,
-   usedExports: false,
-   concatenateModules: false,
-   splitChunks: {
-     hidePathInfo: false,
-     minSize: 10000,
-     maxAsyncRequests: Infinity,
-     maxInitialRequests: Infinity,
-   },
-   noEmitOnErrors: false,
-   checkWasmTypes: false,
-   minimize: false,
- },
- plugins: [
-   new webpack.NamedModulesPlugin(),
-   new webpack.NamedChunksPlugin(),
-   new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("development") }),
- ]
}

mode: 'production'

// webpack.production.config.js
module.exports = {
+  mode: 'production',
- performance: {
-   hints: 'warning'
- },
- output: {
-   pathinfo: false
- },
- optimization: {
-   namedModules: false,
-   namedChunks: false,
-   nodeEnv: 'production',
-   flagIncludedChunks: true,
-   occurrenceOrder: true,
-   sideEffects: true,
-   usedExports: true,
-   concatenateModules: true,
-   splitChunks: {
-     hidePathInfo: true,
-     minSize: 30000,
-     maxAsyncRequests: 5,
-     maxInitialRequests: 3,
-   },
-   noEmitOnErrors: true,
-   checkWasmTypes: true,
-   minimize: true,
- },
- plugins: [
-   new TerserPlugin(/* ... */),
-   new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production") }),
-   new webpack.optimize.ModuleConcatenationPlugin(),
-   new webpack.NoEmitOnErrorsPlugin()
- ]
}

mode: 'none'

// webpack.custom.config.js
module.exports = {
+ mode: 'none',
- performance: {
-  hints: false
- },
- optimization: {
-   flagIncludedChunks: false,
-   occurrenceOrder: false,
-   sideEffects: false,
-   usedExports: false,
-   concatenateModules: false,
-   splitChunks: {
-     hidePathInfo: false,
-     minSize: 10000,
-     maxAsyncRequests: Infinity,
-     maxInitialRequests: Infinity,
-   },
-   noEmitOnErrors: false,
-   checkWasmTypes: false,
-   minimize: false,
- },
- plugins: []
}

由于涉及的选项较多,在后续教程中均会涉及到,现在只需暂时了解即可
参考官网: https://webpack.js.org/config...

下一节:entry与output

阅读 633更新于 2019-05-23

推荐阅读
开水煮前端
用户专栏

带你装逼带你飞

17 人关注
35 篇文章
专栏主页
目录