webpack基本使用

一,webpack基础

  1. 概念,webpack 是一个用于现代 JavaScript 应用程序的静态模块打包工具*。当 webpack 处理应用程序时,它会在内部构建一个 相互依赖图,此依赖图对应映射到项目所需的每个模块,并生成一个或多个 *bundle

  2. 核心概念主要是以下几个方面:

    1. 入口起点(entry),通俗说就是webpack是从那个文件开始的配置方法

      1
      2
      3
      module.exports = {
      entry: './path/to/my/entry/file.js'
      };
    2. 输出(output),就是说通过webpack打包后输出文件放在什么位置,怎么命名

      1
      2
      3
      4
      5
      6
      7
      8
      9
      const path = require('path');

      module.exports = {
      entry: './path/to/my/entry/file.js',
      output: {
      path: path.resolve(__dirname, 'dist'),
      filename: 'my-first-webpack.bundle.js'
      }
      };
    3. 模块加载器(loader),webpack默认只能解析js和json文件,通过各种各样的loader解析器,webpack就可以处理相应的其它类型文件,供应用程序使用,loader有两个属性,test是匹配文件规则,use对于规则使用的加载器

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      const path = require('path');

      module.exports = {
      output: {
      filename: 'my-first-webpack.bundle.js'
      },
      module: {
      rules: [
      { test: /\.txt$/, use: 'raw-loader' }
      ]
      }
      };
    4. 插件(plugin),可以执行更复杂的任务,例如,打包优化,资源管理,注入环境变量等

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      const HtmlWebpackPlugin = require('html-webpack-plugin'); // 通过 npm 安装
      const webpack = require('webpack'); // 用于访问内置插件

      module.exports = {
      module: {
      rules: [
      { test: /\.txt$/, use: 'raw-loader' }
      ]
      },
      plugins: [
      new HtmlWebpackPlugin({template: './src/index.html'})
      ]
      };
    5. 模式(mode),通过选择 development, productionnone 之中的一个,来设置 mode 参数,你可以启用 webpack 内置在相应环境下的优化。其默认值为 production

      1
      2
      3
      module.exports = {
      mode: 'production'
      };

二,常用配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
const path = require('path');

module.exports = {
mode: "production", // "production" | "development" | "none"
// Chosen mode tells webpack to use its built-in optimizations accordingly.
entry: "./app/entry", // string | object | array
// 默认为 ./src
// 这里应用程序开始执行
// webpack 开始打包
output: {
// webpack 如何输出结果的相关选项
path:path.resolve(__dirname, "dist"), // string (default)
// 所有输出文件的目标路径
// 必须是绝对路径(使用 Node.js 的 path 模块)
filename: "[name].js", // string (default)
// entry chunk 的文件名模板
publicPath: "/assets/", // string
// 输出解析文件的目录,url 相对于 HTML 页面
library: { // 这里有一种旧的语法形式可以使用(点击显示)
type: "umd", // 通用模块定义
// the type of the exported library
name: "MyLibrary", // string | string[]
// the name of the exported library
},
uniqueName: "my-application", // (defaults to package.json "name")
// unique name for this build to avoid conflicts with other builds in the same HTML
name: "my-config",
// name of the configuration, shown in output
},
module: {
// 模块配置相关
rules: [
// 模块规则(配置 loader、解析器等选项)
{
// Conditions:
test: /\\.jsx?$/,
include: [
path.resolve(__dirname, "app")
],
exclude: [
path.resolve(__dirname, "app/demo-files")
],
// these are matching conditions, each accepting a regular expression or string
// test and include have the same behavior, both must be matched
// exclude must not be matched (takes preferrence over test and include)
// Best practices:
// - Use RegExp only in test and for filename matching
// - Use arrays of absolute paths in include and exclude to match the full path
// - Try to avoid exclude and prefer include
// Each condition can also receive an object with "and", "or" or "not" properties
// which are an array of conditions.
issuer: /\\.css$/,
issuer: path.resolve(__dirname, "app"),
issuer: { and: [ /\\.css$/, path.resolve(__dirname, "app") ] },
issuer: { or: [ /\\.css$/, path.resolve(__dirname, "app") ] },
issuer: { not: [ /\\.css$/ ] },
issuer: [ /\\.css$/, path.resolve(__dirname, "app") ], // like "or"
// conditions for the issuer (the origin of the import)

// Actions:
loader: "babel-loader",
// 应该应用的 loader,它相对上下文解析
options: {
presets: ["es2015"]
},
// options for the loader
use: [
// apply multiple loaders and options instead
"htmllint-loader",
{
loader: "html-loader",
options: {
// ...
}
}
]
type: "javascript/auto",
// specifies the module type
},
{
oneOf: [
// ... (rules)
]
// only use one of these nested rules
},
{
// ... (conditions)
rules: [
// ... (rules)
]
// use all of these nested rules (combine with conditions to be useful)
},
],
},
resolve: {
// options for resolving module requests
// (does not apply to resolving of loaders)
modules: ["node_modules",path.resolve(__dirname, "app")],
// directories where to look for modules (in order)
extensions: [".js", ".json", ".jsx", ".css"],
// 使用的扩展名
alias: {
// a list of module name aliases
// aliases are imported relative to the current context
"module": "new-module",
// 别名:"module" -> "new-module" 和 "module/path/file" -> "new-module/path/file"
"only-module$": "new-module",
// 别名 "only-module" -> "new-module",但不匹配 "only-module/path/file" -> "new-module/path/file"
"module": path.resolve(__dirname, "app/third/module.js"),
// alias "module" -> "./app/third/module.js" and "module/file" results in error
"module": path.resolve(__dirname, "app/third"),
// alias "module" -> "./app/third" and "module/file" -> "./app/third/file"
[path.resolve(__dirname, "app/module.js")]: path.resolve(__dirname, "app/alternative-module.js"),
// alias "./app/module.js" -> "./app/alternative-module.js"
},
},
performance: {
hints: "warning", // 枚举
maxAssetSize: 200000, // 整数类型(以字节为单位)
maxEntrypointSize: 400000, // 整数类型(以字节为单位)
assetFilter: function(assetFilename) {
// 提供资源文件名的断言函数
return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
}
},
devtool: "source-map", // enum
// 通过为浏览器调试工具提供极其详细的源映射的元信息来增强调试能力,
// 但会牺牲构建速度。
context: __dirname, // string(绝对路径!)
// webpack 的主目录
// entry 和 module.rules.loader 选项
// 都相对于此目录解析
target: "web", // 枚举 node, electron-render electron-main 等,也可以带版本号
// the environment in which the bundle should run
// changes chunk loading behavior, available external modules
// and generated code style
},
devServer: {
proxy: { // proxy URLs to backend development server
'/api': 'http://localhost:3000'
},
contentBase: path.join(__dirname, 'public'), // boolean | string | array, static file location
compress: true, // enable gzip compression
historyApiFallback: true, // true for index.html upon 404, object for multiple paths
hot: true, // hot module replacement. Depends on HotModuleReplacementPlugin
https: false, // true for self-signed, object for cert authority
noInfo: true, // only errors & warns on hot reload
// ...
},
plugins: [
// ...
],
// list of additional plugins
optimization: {
chunkIds: "size",
// method of generating ids for chunks
moduleIds: "size",
// method of generating ids for modules
mangleExports: "size",
// rename export names to shorter names
minimize: true,
// minimize the output files
minimizer: [new CssMinimizer(), "..."],
// minimizers to use for the output files
},