-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
Copy pathbase.js
489 lines (439 loc) · 12.5 KB
/
base.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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
import path from 'path'
import consola from 'consola'
import TimeFixPlugin from 'time-fix-plugin'
import cloneDeep from 'lodash/cloneDeep'
import escapeRegExp from 'lodash/escapeRegExp'
import VueLoader from 'vue-loader'
import ExtractCssChunksPlugin from 'extract-css-chunks-webpack-plugin'
import HardSourcePlugin from 'hard-source-webpack-plugin'
import TerserWebpackPlugin from 'terser-webpack-plugin'
import WebpackBar from 'webpackbar'
import env from 'std-env'
import { isUrl, urlJoin } from '@nuxt/utils'
import PerfLoader from '../utils/perf-loader'
import StyleLoader from '../utils/style-loader'
import WarningIgnorePlugin from '../plugins/warning-ignore'
import { reservedVueTags } from '../utils/reserved-tags'
export default class WebpackBaseConfig {
constructor(builder) {
this.builder = builder
this.buildContext = builder.buildContext
this.modulesToTranspile = this.normalizeTranspile()
}
get colors() {
return {
client: 'green',
server: 'orange',
modern: 'blue'
}
}
get nuxtEnv() {
return {
isDev: this.dev,
isServer: this.isServer,
isClient: !this.isServer,
isModern: Boolean(this.isModern)
}
}
get mode() {
return this.dev ? 'development' : 'production'
}
get dev() {
return this.buildContext.options.dev
}
get loaders() {
return this.buildContext.buildOptions.loaders
}
normalizeTranspile() {
// include SFCs in node_modules
const items = [/\.vue\.js/i]
for (const pattern of this.buildContext.buildOptions.transpile) {
if (pattern instanceof RegExp) {
items.push(pattern)
} else {
const posixModule = pattern.replace(/\\/g, '/')
items.push(new RegExp(escapeRegExp(path.normalize(posixModule))))
}
}
return items
}
getBabelOptions() {
const options = {
...this.buildContext.buildOptions.babel,
envName: this.name
}
if (options.configFile !== false) {
return options
}
const defaultPreset = [
require.resolve('@nuxt/babel-preset-app'),
{
buildTarget: this.isServer ? 'server' : 'client'
}
]
if (typeof options.presets === 'function') {
options.presets = options.presets({ isServer: this.isServer }, defaultPreset)
}
if (!options.babelrc && !options.presets) {
options.presets = [ defaultPreset ]
}
return options
}
getFileName(key) {
let fileName = this.buildContext.buildOptions.filenames[key]
if (typeof fileName === 'function') {
fileName = fileName(this.nuxtEnv)
}
if (this.dev) {
const hash = /\[(chunkhash|contenthash|hash)(?::(\d+))?]/.exec(fileName)
if (hash) {
consola.warn(`Notice: Please do not use ${hash[1]} in dev mode to prevent memory leak`)
}
}
return fileName
}
get devtool() {
return false
}
env() {
const env = {
'process.env.NODE_ENV': JSON.stringify(this.mode),
'process.mode': JSON.stringify(this.mode),
'process.static': this.buildContext.isStatic
}
Object.entries(this.buildContext.options.env).forEach(([key, value]) => {
env['process.env.' + key] =
['boolean', 'number'].includes(typeof value)
? value
: JSON.stringify(value)
})
return env
}
output() {
const {
options: { buildDir, router },
buildOptions: { publicPath }
} = this.buildContext
return {
path: path.resolve(buildDir, 'dist', this.isServer ? 'server' : 'client'),
filename: this.getFileName('app'),
futureEmitAssets: true, // TODO: Remove when using webpack 5
chunkFilename: this.getFileName('chunk'),
publicPath: isUrl(publicPath) ? publicPath : urlJoin(router.base, publicPath)
}
}
optimization() {
const optimization = cloneDeep(this.buildContext.buildOptions.optimization)
if (optimization.minimize && optimization.minimizer === undefined) {
optimization.minimizer = this.minimizer()
}
return optimization
}
resolve() {
// Prioritize nested node_modules in webpack search path (#2558)
const webpackModulesDir = ['node_modules'].concat(this.buildContext.options.modulesDir)
return {
resolve: {
extensions: ['.wasm', '.mjs', '.js', '.json', '.vue', '.jsx', '.ts', '.tsx'],
alias: this.alias(),
modules: webpackModulesDir
},
resolveLoader: {
modules: webpackModulesDir
}
}
}
minimizer() {
const minimizer = []
const { terser, cache } = this.buildContext.buildOptions
// https://github.com/webpack-contrib/terser-webpack-plugin
if (terser) {
minimizer.push(
new TerserWebpackPlugin(Object.assign({
parallel: true,
cache,
sourceMap: this.devtool && /source-?map/.test(this.devtool),
extractComments: {
filename: 'LICENSES'
},
terserOptions: {
compress: {
ecma: this.isModern ? 6 : undefined
},
output: {
comments: /^\**!|@preserve|@license|@cc_on/
},
mangle: {
reserved: reservedVueTags
}
}
}, terser))
)
}
return minimizer
}
alias() {
return {
...this.buildContext.options.alias,
consola: require.resolve(`consola/dist/consola${this.isServer ? '' : '.browser'}.js`)
}
}
rules() {
const perfLoader = new PerfLoader(this.name, this.buildContext)
const styleLoader = new StyleLoader(
this.buildContext,
{ isServer: this.isServer, perfLoader }
)
const babelLoader = {
loader: require.resolve('babel-loader'),
options: this.getBabelOptions()
}
return [
{
test: /\.vue$/i,
loader: 'vue-loader',
options: this.loaders.vue
},
{
test: /\.pug$/i,
oneOf: [
{
resourceQuery: /^\?vue/i,
use: [{
loader: 'pug-plain-loader',
options: this.loaders.pugPlain
}]
},
{
use: [
'raw-loader',
{
loader: 'pug-plain-loader',
options: this.loaders.pugPlain
}
]
}
]
},
{
test: /\.jsx?$/i,
exclude: (file) => {
file = file.split('node_modules', 2)[1]
// not exclude files outside node_modules
if (!file) {
return false
}
// item in transpile can be string or regex object
return !this.modulesToTranspile.some(module => module.test(file))
},
use: perfLoader.js().concat(babelLoader)
},
{
test: /\.ts$/i,
use: [
babelLoader,
{
loader: 'ts-loader',
options: this.loaders.ts
}
]
},
{
test: /\.tsx$/i,
use: [
babelLoader,
{
loader: 'ts-loader',
options: this.loaders.tsx
}
]
},
{
test: /\.css$/i,
oneOf: styleLoader.apply('css')
},
{
test: /\.p(ost)?css$/i,
oneOf: styleLoader.apply('postcss')
},
{
test: /\.less$/i,
oneOf: styleLoader.apply('less', {
loader: 'less-loader',
options: this.loaders.less
})
},
{
test: /\.sass$/i,
oneOf: styleLoader.apply('sass', {
loader: 'sass-loader',
options: this.loaders.sass
})
},
{
test: /\.scss$/i,
oneOf: styleLoader.apply('scss', {
loader: 'sass-loader',
options: this.loaders.scss
})
},
{
test: /\.styl(us)?$/i,
oneOf: styleLoader.apply('stylus', {
loader: 'stylus-loader',
options: this.loaders.stylus
})
},
{
test: /\.(png|jpe?g|gif|svg|webp)$/i,
use: [{
loader: 'url-loader',
options: Object.assign(
this.loaders.imgUrl,
{ name: this.getFileName('img') }
)
}]
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i,
use: [{
loader: 'url-loader',
options: Object.assign(
this.loaders.fontUrl,
{ name: this.getFileName('font') }
)
}]
},
{
test: /\.(webm|mp4|ogv)$/i,
use: [{
loader: 'file-loader',
options: Object.assign(
this.loaders.file,
{ name: this.getFileName('video') }
)
}]
}
]
}
plugins() {
const plugins = []
const { nuxt, buildOptions } = this.buildContext
// Add timefix-plugin before others plugins
if (this.dev) {
plugins.push(new TimeFixPlugin())
}
// CSS extraction)
if (buildOptions.extractCSS) {
plugins.push(new ExtractCssChunksPlugin(Object.assign({
filename: this.getFileName('css'),
chunkFilename: this.getFileName('css')
}, buildOptions.extractCSS)))
}
plugins.push(new VueLoader.VueLoaderPlugin())
plugins.push(...(buildOptions.plugins || []))
plugins.push(new WarningIgnorePlugin(this.warningIgnoreFilter()))
// Build progress indicator
plugins.push(new WebpackBar({
name: this.name,
color: this.colors[this.name],
reporters: [
'basic',
'fancy',
'profile',
'stats'
],
basic: !buildOptions.quiet && env.minimalCLI,
fancy: !buildOptions.quiet && !env.minimalCLI,
profile: !buildOptions.quiet && buildOptions.profile,
stats: !buildOptions.quiet && !this.dev && buildOptions.stats,
reporter: {
change: (_, { shortPath }) => {
if (!this.isServer) {
nuxt.callHook('bundler:change', shortPath)
}
},
done: (buildContext) => {
if (buildContext.hasErrors) {
nuxt.callHook('bundler:error')
}
},
allDone: () => {
nuxt.callHook('bundler:done')
},
progress({ statesArray }) {
nuxt.callHook('bundler:progress', statesArray)
}
}
}))
if (buildOptions.hardSource) {
// https://github.com/mzgoddard/hard-source-webpack-plugin
plugins.push(new HardSourcePlugin({
info: {
level: 'warn'
},
...buildOptions.hardSource
}))
}
return plugins
}
warningIgnoreFilter() {
const { buildOptions, options: { _typescript = {} } } = this.buildContext
const filters = [
// Hide warnings about plugins without a default export (#1179)
warn => warn.name === 'ModuleDependencyWarning' &&
warn.message.includes(`export 'default'`) &&
warn.message.includes('nuxt_plugin_'),
...(buildOptions.warningIgnoreFilters || [])
]
if (_typescript.build && buildOptions.typescript && buildOptions.typescript.ignoreNotFoundWarnings) {
filters.push(
warn => warn.name === 'ModuleDependencyWarning' &&
/export .* was not found in /.test(warn.message)
)
}
return warn => !filters.some(ignoreFilter => ignoreFilter(warn))
}
extendConfig(config) {
const { extend } = this.buildContext.buildOptions
if (typeof extend === 'function') {
const extendedConfig = extend.call(
this.builder, config, { loaders: this.loaders, ...this.nuxtEnv }
)
// Only overwrite config when something is returned for backwards compatibility
if (extendedConfig !== undefined) {
return extendedConfig
}
}
return config
}
config() {
const config = {
name: this.name,
mode: this.mode,
devtool: this.devtool,
optimization: this.optimization(),
output: this.output(),
performance: {
maxEntrypointSize: 1000 * 1024,
hints: this.dev ? false : 'warning'
},
module: {
rules: this.rules()
},
plugins: this.plugins(),
...this.resolve()
}
// Clone deep avoid leaking config between Client and Server
const extendedConfig = cloneDeep(this.extendConfig(config))
const { optimization } = extendedConfig
// Todo remove in nuxt 3 in favor of devtool config property or https://webpack.js.org/plugins/source-map-dev-tool-plugin
if (optimization && optimization.minimizer && extendedConfig.devtool) {
const terser = optimization.minimizer.find(p => p instanceof TerserWebpackPlugin)
if (terser) {
terser.options.sourceMap = /source-?map/.test(extendedConfig.devtool)
}
}
return extendedConfig
}
}