# Webpack-cli
$ npx webpack help
Usage: webpack [entries...] [options]
Alternative usage to run commands: webpack [command] [options]
The build tool for modern web applications.
Options:
-c, --config <value...> Provide path to a webpack configuration file e.g. ./webpack.config.js.
--config-name <value...> Name of the configuration to use.
-m, --merge Merge two or more configurations using 'webpack-merge'.
--env <value...> Environment passed to the configuration when it is a function.
--node-env <value> Sets process.env.NODE_ENV to the specified value.
--progress [value] Print compilation progress during build.
-j, --json [value] Prints result as JSON or store it in a file.
-d, --devtool <value> Determine source maps to use.
--no-devtool Do not generate source maps.
--entry <value...> The entry point(s) of your application e.g. ./src/main.js.
--mode <value> Defines the mode to pass to webpack.
--name <value> Name of the configuration. Used when loading multiple configurations.
-o, --output-path <value> Output location of the file generated by webpack e.g. ./dist/.
--stats [value] It instructs webpack on how to treat the stats e.g. verbose.
--no-stats Disable stats output.
-t, --target <value...> Sets the build target e.g. node.
--no-target Negative 'target' option.
-w, --watch Watch for files changes.
--no-watch Do not watch for file changes.
--watch-options-stdin Stop watching when stdin stream has ended.
--no-watch-options-stdin Do not stop watching when stdin stream has ended.
Global options:
--color Enable colors on console.
--no-color Disable colors on console.
-v, --version Output the version number of 'webpack', 'webpack-cli' and 'webpack-dev-server' and commands.
-h, --help [verbose] Display help for commands and options.
Commands:
build|bundle|b [entries...] [options] Run webpack (default command, can be omitted).
configtest|t [config-path] Validate a webpack configuration.
help|h [command] [option] Display help for commands and options.
info|i [options] Outputs information about your system.
serve|server|s [entries...] Run the webpack dev server. To see all available options you need to install 'webpack', 'webpack-dev-server'.
version|v [commands...] Output the version number of 'webpack', 'webpack-cli' and 'webpack-dev-server' and commands.
watch|w [entries...] [options] Run webpack and watch for files changes.
To see list of all supported commands and options run 'webpack --help=verbose'.
Webpack documentation: https://webpack.js.org/.
CLI documentation: https://webpack.js.org/api/cli/.
Made with ♥ by the webpack team.
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
# Cli命令行打包
https://www.webpackjs.com/api/cli/#%E7%A4%BA%E4%BE%8B%E7%94%A8%E6%B3%95
使用配置文件:
webpack [--config webpack.config.js]
不使用配置文件:
webpack <entry> [<entry>] -o <output>
# example
webpack --mode development ./src/index.js -o ./dist/bundle.js
2
3
webpack.config.js
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 // 这里应用程序开始执行
// webpack 开始打包
output: {
// webpack 如何输出结果的相关选项
path: path.resolve(__dirname, "dist"), // string
// 所有输出文件的目标路径
// 必须是绝对路径(使用 Node.js 的 path 模块)
filename: "bundle.js", // string // 「入口分块(entry chunk)」的文件名模板(出口分块?)
publicPath: "/assets/", // string // 输出解析文件的目录,url 相对于 HTML 页面
library: "MyLibrary", // string,
// 导出库(exported library)的名称
libraryTarget: "umd", // 通用模块定义 // 导出库(exported library)的类型
/* 高级输出配置(点击显示) */ },
module: {
// 关于模块配置
rules: [
// 模块规则(配置 loader、解析器等选项)
{
test: /\.jsx?$/,
include: [
path.resolve(__dirname, "app")
],
exclude: [
path.resolve(__dirname, "app/demo-files")
],
// 这里是匹配条件,每个选项都接收一个正则表达式或字符串
// test 和 include 具有相同的作用,都是必须匹配选项
// exclude 是必不匹配选项(优先于 test 和 include)
// 最佳实践:
// - 只在 test 和 文件名匹配 中使用正则表达式
// - 在 include 和 exclude 中使用绝对路径数组
// - 尽量避免 exclude,更倾向于使用 include
issuer: { test, include, exclude },
// issuer 条件(导入源)
enforce: "pre",
enforce: "post",
// 标识应用这些规则,即使规则覆盖(高级选项)
loader: "babel-loader",
// 应该应用的 loader,它相对上下文解析
// 为了更清晰,`-loader` 后缀在 webpack 2 中不再是可选的
// 查看 webpack 1 升级指南。
options: {
presets: ["es2015"]
},
// loader 的可选项
},
{
test: /\.html$/,
test: "\.html$"
use: [
// 应用多个 loader 和选项
"htmllint-loader",
{
loader: "html-loader",
options: {
/* ... */
}
}
]
},
{ oneOf: [ /* rules */ ] },
// 只使用这些嵌套规则之一
{ rules: [ /* rules */ ] },
// 使用所有这些嵌套规则(合并可用条件)
{ resource: { and: [ /* 条件 */ ] } },
// 仅当所有条件都匹配时才匹配
{ resource: { or: [ /* 条件 */ ] } },
{ resource: [ /* 条件 */ ] },
// 任意条件匹配时匹配(默认为数组)
{ resource: { not: /* 条件 */ } }
// 条件不匹配时匹配
],
/* 高级模块配置(点击展示) */ },
resolve: {
// 解析模块请求的选项
// (不适用于对 loader 解析)
modules: [
"node_modules",
path.resolve(__dirname, "app")
],
// 用于查找模块的目录
extensions: [".js", ".json", ".jsx", ".css"],
// 使用的扩展名
alias: {
// 模块别名列表
"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"),
// 起别名 "module" -> "./app/third/module.js" 和 "module/file" 会导致错误
// 模块别名相对于当前上下文导入
},
/* 可供选择的别名语法(点击展示) */
/* 高级解析选项(点击展示) */ },
performance: {
hints: "warning", // 枚举 maxAssetSize: 200000, // 整数类型(以字节为单位)
maxEntrypointSize: 400000, // 整数类型(以字节为单位)
assetFilter: function(assetFilename) {
// 提供资源文件名的断言函数
return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
}
},
devtool: "source-map", // enum // 通过在浏览器调试工具(browser devtools)中添加元信息(meta info)增强调试
// 牺牲了构建速度的 `source-map' 是最详细的。
context: __dirname, // string(绝对路径!)
// webpack 的主目录
// entry 和 module.rules.loader 选项
// 相对于此目录解析
target: "web", // 枚举 // 包(bundle)应该运行的环境
// 更改 块加载行为(chunk loading behavior) 和 可用模块(available module)
externals: ["react", /^@angular\//], // 不要遵循/打包这些模块,而是在运行时从环境中请求他们
stats: "errors-only", // 精确控制要显示的 bundle 信息
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: [
// ...
],
// 附加插件列表
/* 高级配置(点击展示) */}
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
166
167
168
169
170
171
# Output:
https://webpack.docschina.org/concepts/#output
在 webpack 的配置中,loader 有两个属性:
test属性,识别出哪些文件会被转换。use属性,定义出在进行转换时,应该使用哪个 loader。
const path = require('path');
module.exports = {
output: {
filename: 'my-first-webpack.bundle.js'
},
module: {
rules: [
{ test: /\.txt$/, use: 'raw-loader' }
]
}
};
2
3
4
5
6
7
8
9
10
11
12
以上配置中,对一个单独的 module 对象定义了 rules 属性,里面包含两个必须属性:test 和 use。这告诉 webpack 编译器(compiler) 如下信息:
“嘿,webpack 编译器,当你碰到「在
require()/import语句中被解析为 '.txt' 的路径」时,在你对它打包之前,先 use(使用)raw-loader转换一下。”
# publicPath
output.publicPath (opens new window)
部署应用包时的基本 URL。和服务器资源路径无关。
const router = new Router({
mode: 'hash',
base: '/my-app/', // 设置 base 路径
routes: [ /* 路由配置 */ ]
})
2
3
4
5
如果设置了router的base,则也要设置 publicPath 为 /my-app/
如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://www.my-app.com/my-app/,则设置 publicPath 为 /my-app/。
vue-router 的base设置为/app-vue 后,output.publicPath也应设置为同样的值,这样才能确保资源访问时的引用路径正确
打包后资源的引用路径,比如js的引用。当publicPath设置为'static'后
<script defer="" src="static/index_bundle.js?71355401d52ef93ee2a0"></script>
而对应的文件名也需要修改
// 原来
filename: 'index_bundle.js',
// 修改为
filename: ''
2
3
4
⚠️注意事项:相对 publicPath 的限制
相对路径的
publicPath有一些使用上的限制。在以下情况下,应当避免使用相对publicPath:
- 当使用基于 HTML5
history.pushState的路由时;即mode: 'history'时- 当使用
pages选项构建多页面应用时。
# output.filename (opens new window)
使用相对路径
此选项决定了每个输出 bundle 的名称。这些 bundle 将写入到
output.path(opens new window) 选项指定的目录下。
# output.path
output 目录对应一个绝对路径。
output: {
clean: true,
path: path.resolve(__dirname, process.env.publicPath ?? '/', './dist'),
filename: 'js/[name].[contenthash].bundle.js',
publicPath: process.env.publicPath ?? '/'
},
2
3
4
5
6
# resolve:
# resolve.alias
路径别名
# modules
模块配置,来看一段规则:
{
test: /\.html$/,
test: '.html$',
use: [
// 应用多个 loader 和选项
'htmllint-loader',
{
loader: 'html-loader',
options: {
/* ... */
},
},
],
},
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# rules
https://segmentfault.com/a/1190000013145176
1. 条件匹配: 通过test、include、exclude三个配置来命中Loader要应用的规则文件。
2. 应用规则: 对选中后的文件通过use配置项来应用loader,可以应用一个loader或者按照从后往前的顺序应用一组loader。同时还可以分别给loader传入参数。
3. 重置顺序: 一组loader的执行顺序默认是从有道左执行,通过exforce选项可以让其中一个loader的执行顺序放到最前或者是最后。
2
3
# rules条件
https://webpack.docschina.org/configuration/module/#rule-conditions
# optimization
# devServer
https://webpack.docschina.org/configuration/dev-server/#root
# proxy (opens new window)
devServer: {
proxy: 'https://192.168.0.183' // 代理到https://192.168.0.183上
}
2
3
# devtool
sourcemap模式
具体查看这篇文章
https://juejin.cn/post/6844904201311485966#heading-20
- eval
- eval-source-map
- eval-cheap-source-map
- eval-cheap-module-source-map
# devServer.historyApiFallback (opens new window)
使用HTML5 History API 时 (opens new window),index.html可能必须提供页面来代替任何404响应。devServer.historyApiFallback通过将其设置为启用true
module.exports = {
//...
devServer: {
historyApiFallback: true,
},
};
2
3
4
5
6