-
Notifications
You must be signed in to change notification settings - Fork 0
/
webpack.config.js
474 lines (422 loc) · 12 KB
/
webpack.config.js
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
const path = require('path')
const fs = require('fs')
const webpack = require('webpack')
// webpack配置项:https://webpack.js.org/configuration/
class Webpack5RecommendConfig {
constructor(env, argv) {
this.mode = argv.mode || 'development' // 模式
this.isProduction = this.mode === 'production' // 是否为开发环境
this.cwd = process.cwd() // 当前运行webpack所在位置
this.srcPath = path.resolve(this.cwd, 'src') // 源码目录文件位置
this.distPath = path.resolve(this.cwd, 'dist') // 输出文件位置
this.publicPath = '/' // 发布时URL访问路径
this.packageJSON = require(path.join(this.cwd, 'package.json')) // package.json文件信息对象
this.dependencies = Object.keys({ // 项目依赖库数组,用于判定包含什么框架
...this.packageJSON['devDependencies'],
...this.packageJSON['dependencies']
})
this.isTsProject = fs.existsSync(path.join(this.cwd, 'tsconfig.json')) // 是否为ts项目
this.scriptExt = this.isTsProject ? '.ts' : '.js' // 入口脚本扩展名称
this.entryDefaultName = 'main' // 入口默认名,webpack默认入口为index.js,输出为main.js
this.entryDefaultFileName = `${this.entryDefaultName}${this.scriptExt}` // 入口文件默认名称
this.existsStaticFolderPath = fs.existsSync(path.join(this.cwd, 'public')) // 是否存在public目录
this.title = 'Webpack App' // 主页标题
this.enableProfile = false // 是否统计并打印webpack打包详细信息
this.enableProxy = false // 是否启用代理配置
this.enableThread = true // 是否启用多线程
this.enableBalbel = this.isProduction // 生产环境启用babel做编译
this.config = {}
}
build() {
// webpack5配置文档:https://webpack.js.org/configuration/
this.buildBasic()
this.buildInsAndOuts()
this.buildResolve()
this.buildDevServer()
this.buildImprove()
this.buildRules()
this.buildPlugins()
return this
}
buildBasic() {
this.config.mode = this.mode
this.config.stats = 'errors-only'
this.config.devtool = this.isProduction ? false : 'eval-source-map'
this.config.context = this.cwd
if (!this.isProduction) {
this.config.target = 'web' // 默认值:browserslist
}
return this
}
buildInsAndOuts() {
this.config.entry = {
[this.entryDefaultName]: path.join(this.srcPath, this.entryDefaultFileName)
}
this.config.output = {
filename: '[name].bundle.[chunkhash:8].js',
chunkFilename: '[name].chunk.[chunkhash:8].js',
assetModuleFilename: 'assets/[name][hash][ext]',
path: this.distPath,
publicPath: this.publicPath,
compareBeforeEmit: false,
iife: true,
clean: true
}
return this
}
buildResolve() {
this.config.resolve = {
extensions: ['.js'],
alias: {
'@': path.join(this.cwd, 'src')
}
}
if (this.isTsProject) {
this.config.resolve.extensions.push('.ts')
}
if (this.dependencies.includes('react')) {
this.config.resolve.extensions.push('.jsx')
if (this.isTsProject) {
this.config.resolve.extensions.push('.tsx')
}
}
if (this.dependencies.includes('vue')) {
this.config.resolve.extensions.push('.vue')
}
return this
}
buildDevServer() {
// https://webpack.js.org/configuration/dev-server/
let port = 8080
this.config.devServer = {
allowedHosts: 'all',
historyApiFallback: false,
host: '0.0.0.0',
liveReload: true,
hot: true, // HMR(Hot Module Replacement),JS文件内需要调用accept()
open: [`http:https://localhost:${port}/`],
port: port,
magicHtml: false,
// https://github.com/webpack/webpack-dev-middleware
devMiddleware: {
stats: false
}
}
if (this.enableProxy) {
this.config.devServer.proxy = this.configProxy()
}
return this
}
buildImprove() {
this.config.performance = {
hints: 'warning',
maxAssetSize: (this.isProduction ? 3 : 30) * 1024 * 1024,
maxEntrypointSize: (this.isProduction ? 3 : 30) * 1024 * 1024
}
/**
* https://webpack.js.org/plugins/split-chunks-plugin/#configuration
*
* 产生chunk的3种方式
* 1. 手动设置规则进行切割
* 2. 多个入口文件会被当成多个Chunk处理
* 3. 使用import()进行异步导入
*/
this.config.optimization = {
splitChunks: {
/**
* all: 所有方式引入的Module中的符合手动切割Chunk规则的Module都会被解析分离
* initial: 异步引入的Module中符合手动切割Chunk规则的Module不做解析分离
* async: 同步引入的Module中符合手动切割Chunk规则的Module不做解析分离
*/
chunks: 'all',
automaticNameDelimiter: '~',
cacheGroups: this.getSplitChunksGroup()
},
minimize: this.isProduction,
minimizer: [
new (require('terser-webpack-plugin'))() //
]
}
if (this.isProduction) {
this.config.optimization.runtimeChunk = 'single'
}
return this
}
buildRules() {
this.config.module = {rules: []}
/**
* 添加js解析
*/
let jsUse = this.enableBalbel ? ['babel-loader'] : []
if (this.enableThread) {
jsUse.unshift('thread-loader')
}
this.config.module.rules.push({
test: /\.js$/,
exclude: /[\\/]node_modules[\\/]/,
use: jsUse
})
/**
* 添加jsx解析
*/
let jsxUse = this.enableBalbel ? ['babel-loader'] : []
if (this.enableThread) {
jsxUse.unshift('thread-loader')
}
this.config.module.rules.push({
test: /\.jsx$/,
use: jsxUse
})
if (this.isTsProject) {
/**
* 添加ts/tsx解析
*/
let tsUse = this.enableBalbel ? ['babel-loader'] : []
tsUse.push({
loader: 'ts-loader',
options: {
// https://github.com/TypeStrong/ts-loader#happypackmode
happyPackMode: this.enableThread,
transpileOnly: true,
compilerOptions: {
jsx: this.isProduction ? 'preserve' : 'react-jsxdev',
noEmit: true
}
}
})
if (this.enableThread) {
tsUse.unshift('thread-loader')
}
this.config.module.rules.push({
test: /\.tsx?$/,
use: tsUse
})
}
/**
* 添加css解析
*/
this.config.module.rules.push({
test: /\.css$/,
use: this.getCssLoader()
})
/**
* 添加sass解析
*/
this.config.module.rules.push({
test: /\.s[ca]ss$/,
use: this.getCssLoader('sass')
})
/**
* https://webpack.js.org/guides/asset-modules/
*
* 添加图片资源解析
*/
this.config.module.rules.push({
test: /\.(png|jpe?g|gif|svg)$/,
type: 'asset',
generator: {
filename: 'images/[name].[hash][ext]'
}
})
/**
* https://webpack.js.org/guides/asset-modules/
*
* 添加媒体资源解析
*/
this.config.module.rules.push({
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
type: 'asset',
generator: {
filename: 'media/[name].[hash][ext]'
}
})
/**
* https://webpack.js.org/guides/asset-modules/
*
* 添加字体资源解析
*/
this.config.module.rules.push({
test: /\.(woff|woff2|eot|ttf|otf)$/,
type: 'asset',
generator: {
filename: 'font/[name].[hash][ext]'
}
})
return this
}
buildPlugins() {
this.config.plugins = []
if (this.isProduction) {
/**
* 将 CSS 提取到单独的文件中
* https://webpack.js.org/plugins/mini-css-extract-plugin/
*/
this.config.plugins.push(
new (require('mini-css-extract-plugin'))({
filename: '[name].style.[chunkhash:8].css'
})
)
}
/**
* 自动添加HTML插件
* https://github.com/jantimon/html-webpack-plugin
*/
let htmWebpackPluginOptions = {
tittle: this.title,
filename: 'index.html',
inject: 'body',
hash: false,
// https://github.com/terser/html-minifier-terser
minify: this.isProduction
? {
removeComments: true,
collapseWhitespace: true,
minifyCSS: true
}
: false
}
this.config.plugins.push(new (require('html-webpack-plugin'))(htmWebpackPluginOptions))
if (this.existsStaticFolderPath) {
/**
* 将已存在的单个文件或整个目录复制到构建目录
* https://webpack.js.org/plugins/copy-webpack-plugin
*/
this.config.plugins.push(
new (require('copy-webpack-plugin'))({
patterns: [
{
from: path.join(this.cwd, 'public'),
to: '.'
}
]
})
)
}
if (this.enableProfile) {
/**
* Elegant ProgressBar and Profiler for Webpack 3 , 4 and 5
* https://github.com/unjs/webpackbar
*/
this.config.plugins.push(
new (require('webpackbar'))({
reporters: ['fancy', 'profile'],
profile: true
})
)
} else {
this.config.plugins.push(new (require('webpackbar'))())
}
/**
* 允许在编译时配置全局常量
* https://webpack.js.org/plugins/define-plugin
*/
this.config.plugins.push(
new webpack.DefinePlugin({
webpack5RecommendConfigOptions: {
author: '"SystemLight"'
}
})
)
/**
* 在监视模式下忽略指定的文件
* https://webpack.js.org/plugins/watch-ignore-plugin/
*/
let ignorePaths = []
if (this.isTsProject) {
// https://github.com/TypeStrong/ts-loader#usage-with-webpack-watch
ignorePaths.push(/\.js$/, /\.d\.ts$/)
this.config.plugins.push(
new webpack.WatchIgnorePlugin({
paths: ignorePaths
})
)
}
return this
}
getSplitChunksGroup() {
// 内置定义Chunk切割分离规则
let cacheGroups = {
common: {
name: 'common',
minChunks: 2,
reuseExistingChunk: true,
priority: -20
},
vendors: {
name: 'vendors',
test: /[\\/]node_modules[\\/]/,
priority: -10
}
}
if (this.dependencies.includes('vue')) {
Object.assign(cacheGroups, {
vue: {
name: 'vue',
test: /[\\/]node_modules[\\/](vue|vue-router|vuex)/,
chunks: 'all',
enforce: true
}
})
}
if (this.dependencies.includes('element-ui')) {
Object.assign(cacheGroups, {
elementUI: {
name: 'element-ui',
test: /[\\/]node_modules[\\/](element-ui)/,
chunks: 'all'
}
})
}
if (this.dependencies.includes('react')) {
Object.assign(cacheGroups, {
react: {
name: 'react',
test: /[\\/]node_modules[\\/](react|react-dom|scheduler|prop-types)/,
chunks: 'all'
}
})
}
if (this.dependencies.includes('antd')) {
cacheGroups = Object.assign(cacheGroups, {
antd: {
name: 'antd',
test: /[\\/]node_modules[\\/](@ant-design|antd)/,
chunks: 'all'
}
})
}
return cacheGroups
}
getCssLoader(cssPreprocessing) {
let cssRuleLoaders = []
if (this.isProduction) {
cssRuleLoaders.push(require('mini-css-extract-plugin').loader)
} else {
cssRuleLoaders.push('style-loader')
}
cssRuleLoaders.push('css-loader')
switch (cssPreprocessing) {
case 'sass':
cssRuleLoaders.push('sass-loader')
break
}
return cssRuleLoaders
}
configProxy() {
return {
// https://github.com/chimurai/http-proxy-middleware
'/api': {
target: 'http:https://localhost:5000/api',
changeOrigin: true,
secure: false
}
}
}
toConfig(debug) {
if (debug) {
console.log(this.config)
}
return this.config
}
}
module.exports = (env, argv) => new Webpack5RecommendConfig(env, argv).build().toConfig()