0%

webapckFile

webpackCli

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
Usage: webpack serve|server|s [entries...] [options]

Run the webpack dev server.

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.
--watch-options-stdin Stop watching when stdin stream has ended.
--no-watch-options-stdin Do not stop watching when stdin stream has ended.
--bonjour Broadcasts the server via ZeroConf networking on
start
--lazy Lazy
--liveReload Enables/Disables live reloading on changing files
--serveIndex Enables/Disables serveIndex middleware
--inline Inline mode (set to false to disable including
client scripts like livereload)
--profile Print compilation profile data for progress steps
--progress Print compilation progress in percentage
--hot-only Do not refresh page if HMR fails
--stdin close when stdin ends
--open [value] Open the default browser, or optionally specify a
browser name
--useLocalIp Open default browser with local IP
--open-page <value> Open default browser with the specified page
--client-log-level <value> Log level in the browser (trace, debug, info,
warn, error or silent)
--https HTTPS
--http2 HTTP/2, must be used with HTTPS
--key <value> Path to a SSL key.
--cert <value> Path to a SSL certificate.
--cacert <value> Path to a SSL CA certificate.
--pfx <value> Path to a SSL pfx file.
--pfx-passphrase <value> Passphrase for pfx file.
--content-base <value> A directory or URL to serve HTML content from.
--watch-content-base Enable live-reloading of the content-base.
--history-api-fallback Fallback to /index.html for Single Page
Applications.
--compress Enable gzip compression
--port <value> The port
--disable-host-check Will not check the host
--socket <value> Socket to listen
--public <value> The public hostname/ip address of the server
--host <value> The hostname/ip address the server will bind to
--allowed-hosts <value...> A list of hosts that are allowed to access the
dev server, separated by spaces

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.

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.

webapck 开发环境代码:

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
// resolve用来拼接绝对路径的方法
const { resolve } = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin') // 引用plugin

module.exports = {
// webpack配置
entry: './src/js/index.js', // 入口起点
output: {
// 输出
// 输出文件名
filename: 'js/build.js',
// __dirname是nodejs的变量,代表当前文件的目录绝对路径
path: resolve(__dirname, 'build'), // 输出路径,所有资源打包都会输出到这个文件夹下
},
// loader配置
module: {
rules: [
// 详细的loader配置
// 不同文件必须配置不同loader处理
{
// 匹配哪些文件
test: /\.less$/,
// 使用哪些loader进行处理
use: [
// use数组中loader执行顺序:从右到左,从下到上,依次执行(先执行css-loader)
// style-loader:创建style标签,将js中的样式资源插入进去,添加到head中生效
'style-loader',
// css-loader:将css文件变成commonjs模块加载到js中,里面内容是样式字符串
'css-loader',
// less-loader:将less文件编译成css文件,需要下载less-loader和less
'less-loader'
],
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
// url-loader:处理图片资源,问题:默认处理不了html中的img图片
test: /\.(jpg|png|gif)$/,
// 需要下载 url-loader file-loader
loader: 'url-loader',
options: {
// 图片大小小于8kb,就会被base64处理,优点:减少请求数量(减轻服务器压力),缺点:图片体积会更大(文件请求速度更慢)
// base64在客户端本地解码所以会减少服务器压力,如果图片过大还采用base64编码会导致cpu调用率上升,网页加载时变卡
limit: 8 * 1024,
// 给图片重命名,[hash:10]:取图片的hash的前10位,[ext]:取文件原来扩展名
name: '[hash:10].[ext]',
// 问题:因为url-loader默认使用es6模块化解析,而html-loader引入图片是conmonjs,解析时会出问题:[object Module]
// 解决:关闭url-loader的es6模块化,使用commonjs解析
esModule: false,
outputPath: 'imgs',
},
},
{
test: /\.html$/,
// 处理html文件的img图片(负责引入img,从而能被url-loader进行处理)
loader: 'html-loader',
},
// 打包其他资源(除了html/js/css资源以外的资源)
{
// 排除html|js|css|less|jpg|png|gif文件
exclude: /\.(html|js|css|less|jpg|png|gif)/,
// file-loader:处理其他文件
loader: 'file-loader',
options: {
name: '[hash:10].[ext]',
outputPath: 'media',
},
},
],
},
// plugin的配置
plugins: [
// html-webpack-plugin:默认会创建一个空的html文件,自动引入打包输出的所有资源(JS/CSS)
// 需要有结构的HTML文件可以加一个template
new HtmlWebpackPlugin({
// 复制这个./src/index.html文件,并自动引入打包输出的所有资源(JS/CSS)
template: './src/index.html',
}),
],
// 模式
mode: 'development', // 开发模式
// 开发服务器 devServer:用来自动化,不用每次修改后都重新输入webpack打包一遍(自动编译,自动打开浏览器,自动刷新浏览器)
// 特点:只会在内存中编译打包,不会有任何输出(不会像之前那样在外面看到打包输出的build包,而是在内存中,关闭后会自动删除)
// 启动devServer指令为:npx webpack-dev-server
devServer: {
// 项目构建后路径
contentBase: resolve(__dirname, 'build'),
// 启动gzip压缩
compress: true,
// 端口号
port: 3000,
// 自动打开浏览器
open: true,
},
}

webapck生产环境代码:

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
166
167
168
169
170
171
172
const { resolve } = require('path')
const MiniCssExtractorPlugin = require('mini-css-extract-plugin')
const OptimiziCssAssetsWebpackPlugin = require('optimizi-css-assets-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')

// 定义node.js的环境变量,决定使用browserslist的哪个环境
process.env.NODE_ENV = 'production'

// 复用loader的写法
const commonCssLoader = [
// 这个loader取代style-loader。作用:提取js中的css成单独文件然后通过link加载
MiniCssExtractPlugin.loader,
// css-loader:将css文件整合到js文件中
// 经过css-loader处理后,样式文件是在js文件中的
// 问题:1.js文件体积会很大2.需要先加载js再动态创建style标签,样式渲染速度就慢,会出现闪屏现象
// 解决:用MiniCssExtractPlugin.loader替代style-loader
'css-loader',
/*
postcss-loader:css兼容性处理:postcss --> 需要安装:postcss-loader postcss-preset-env
postcss需要通过package.json中browserslist里面的配置加载指定的css兼容性样式
在package.json中定义browserslist:
"browserslist": {
// 开发环境 --> 设置node环境变量:process.env.NODE_ENV = development
"development": [ // 只需要可以运行即可
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
],
// 生产环境。默认是生产环境
"production": [ // 需要满足绝大多数浏览器的兼容
">0.2%",
"not dead",
"not op_mini all"
]
},
*/
{
loader: 'postcss-loader',
options: {
ident: 'postcss', // 基本写法
plugins: () => [
// postcss的插件
require('postcss-preset-env')(),
],
},
},
]

module.exports = {
entry: './src/js/index.js',
output: {
filename: 'js/built.js',
path: resolve(__dirname, 'build'),
},
module: {
rules: [
{
test: /\.css$/,
use: [...commonCssLoader],
},
{
test: /\.less$/,
use: [...commonCssLoader, 'less-loader'],
},
/*
正常来讲,一个文件只能被一个loader处理
当一个文件要被多个loader处理,那么一定要指定loader执行的先后顺序
先执行eslint再执行babel(用enforce)
*/
{
/*
js的语法检查: 需要下载 eslint-loader eslint
注意:只检查自己写的源代码,第三方的库是不用检查的
airbnb(一个流行的js风格) --> 需要下载 eslint-config-airbnb-base eslint-plugin-import
设置检查规则:
package.json中eslintConfig中设置
"eslintConfig": {
"extends": "airbnb-base", // 继承airbnb的风格规范
"env": {
"browser": true // 可以使用浏览器中的全局变量(使用window不会报错)
}
}
*/
test: /\.js$/,
exclude: /node_modules/, // 忽略node_modules
enforce: 'pre', // 优先执行
loader: 'eslint-loader',
options: {
// 自动修复
fix: true,
},
},
/*
js兼容性处理:需要下载 babel-loader @babel/core
1. 基本js兼容性处理 --> @babel/preset-env
问题:只能转换基本语法,如promise高级语法不能转换
2. 全部js兼容性处理 --> @babel/polyfill
问题:只要解决部分兼容性问题,但是将所有兼容性代码全部引入,体积太大了
3. 需要做兼容性处理的就做:按需加载 --> core-js
*/
{
// 第三种方式:按需加载
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
// 预设:指示babel做怎样的兼容性处理
presets: [
'@babel/preset-env', // 基本预设
{
useBuiltIns: 'usage', //按需加载
corejs: { version: 3 }, // 指定core-js版本
targets: { // 指定兼容到什么版本的浏览器
chrome: '60',
firefox: '50',
ie: '9',
safari: '10',
edge: '17'
},
},
],
},
},
{
// 图片处理
test: /\.(jpg|png|gif)/,
loader: 'url-loader',
options: {
limit: 8 * 1024,
name: '[hash:10].[ext]',
outputPath: 'imgs',
esModule: false, // 关闭url-loader默认使用的es6模块化解析
},
},
// html中的图片处理
{
test: /\.html$/,
loader: 'html-loader',
},
// 处理其他文件
{
exclude: /\.(js|css|less|html|jpg|png|gif)/,
loader: 'file-loader',
options: {
outputPath: 'media',
},
},
],
},
plugins: [
new MiniCssExtractPlugin({
// 对输出的css文件进行重命名
filename: 'css/built.css',
}),
// 压缩css
new OptimiziCssAssetsWebpackPlugin(),
// HtmlWebpackPlugin:html文件的打包和压缩处理
// 通过这个插件会自动将单独打包的样式文件通过link标签引入
new HtmlWebpackPlugin({
template: './src/index.html',
// 压缩html代码
minify: {
// 移除空格
collapseWhitespace: true,
// 移除注释
removeComments: true,
},
}),
],
// 生产环境下会自动压缩js代码
mode: 'production',
}

来源博客