-
-
Notifications
You must be signed in to change notification settings - Fork 6.3k
/
Copy pathapp.js
308 lines (277 loc) · 9.67 KB
/
app.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
// config that are specific to --target app
const fs = require('fs')
const path = require('path')
// ensure the filename passed to html-webpack-plugin is a relative path
// because it cannot correctly handle absolute paths
function ensureRelative (outputDir, _path) {
if (path.isAbsolute(_path)) {
return path.relative(outputDir, _path)
} else {
return _path
}
}
module.exports = (api, options) => {
api.chainWebpack(webpackConfig => {
// only apply when there's no alternative target
if (process.env.VUE_CLI_BUILD_TARGET && process.env.VUE_CLI_BUILD_TARGET !== 'app') {
return
}
const isProd = process.env.NODE_ENV === 'production'
const isLegacyBundle = process.env.VUE_CLI_MODERN_MODE && !process.env.VUE_CLI_MODERN_BUILD
const outputDir = api.resolve(options.outputDir)
const getAssetPath = require('../util/getAssetPath')
const outputFilename = getAssetPath(
options,
`js/[name]${isLegacyBundle ? `-legacy` : ``}${isProd && options.filenameHashing ? '.[contenthash:8]' : ''}.js`
)
webpackConfig
.output
.filename(outputFilename)
.chunkFilename(outputFilename)
// code splitting
if (process.env.NODE_ENV !== 'test') {
webpackConfig
.optimization.splitChunks({
cacheGroups: {
vendors: {
name: `chunk-vendors`,
test: /[\\/]node_modules[\\/]/,
priority: -10,
chunks: 'initial'
},
common: {
name: `chunk-common`,
minChunks: 2,
priority: -20,
chunks: 'initial',
reuseExistingChunk: true
}
}
})
}
// HTML plugin
const resolveClientEnv = require('../util/resolveClientEnv')
// #1669 html-webpack-plugin's default sort uses toposort which cannot
// handle cyclic deps in certain cases. Monkey patch it to handle the case
// before we can upgrade to its 4.0 version (incompatible with preload atm)
const chunkSorters = require('html-webpack-plugin/lib/chunksorter')
const depSort = chunkSorters.dependency
chunkSorters.auto = chunkSorters.dependency = (chunks, ...args) => {
try {
return depSort(chunks, ...args)
} catch (e) {
// fallback to a manual sort if that happens...
return chunks.sort((a, b) => {
// make sure user entry is loaded last so user CSS can override
// vendor CSS
if (a.id === 'app') {
return 1
} else if (b.id === 'app') {
return -1
} else if (a.entry !== b.entry) {
return b.entry ? -1 : 1
}
return 0
})
}
}
const htmlOptions = {
title: api.service.pkg.name,
templateParameters: (compilation, assets, pluginOptions) => {
// enhance html-webpack-plugin's built in template params
let stats
return Object.assign({
// make stats lazy as it is expensive
get webpack () {
return stats || (stats = compilation.getStats().toJson())
},
compilation: compilation,
webpackConfig: compilation.options,
htmlWebpackPlugin: {
files: assets,
options: pluginOptions
}
}, resolveClientEnv(options, true /* raw */))
}
}
// handle indexPath
if (options.indexPath !== 'index.html') {
// why not set filename for html-webpack-plugin?
// 1. It cannot handle absolute paths
// 2. Relative paths causes incorrect SW manifest to be generated (#2007)
webpackConfig
.plugin('move-index')
.use(require('../webpack/MovePlugin'), [
path.resolve(outputDir, 'index.html'),
path.resolve(outputDir, options.indexPath)
])
}
if (isProd) {
Object.assign(htmlOptions, {
minify: {
removeComments: true,
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeScriptTypeAttributes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
}
})
// keep chunk ids stable so async chunks have consistent hash (#1916)
webpackConfig
.plugin('named-chunks')
.use(require('webpack/lib/NamedChunksPlugin'), [chunk => {
if (chunk.name) {
return chunk.name
}
const hash = require('hash-sum')
const joinedHash = hash(
Array.from(chunk.modulesIterable, m => m.id).join('_')
)
return `chunk-` + joinedHash
}])
}
// resolve HTML file(s)
const HTMLPlugin = require('html-webpack-plugin')
const PreloadPlugin = require('@vue/preload-webpack-plugin')
const multiPageConfig = options.pages
const htmlPath = api.resolve('public/index.html')
const defaultHtmlPath = path.resolve(__dirname, 'index-default.html')
const publicCopyIgnore = ['**/.DS_Store']
if (!multiPageConfig) {
// default, single page setup.
htmlOptions.template = fs.existsSync(htmlPath)
? htmlPath
: defaultHtmlPath
publicCopyIgnore.push(api.resolve(htmlOptions.template).replace(/\\/g, '/'))
webpackConfig
.plugin('html')
.use(HTMLPlugin, [htmlOptions])
if (!isLegacyBundle) {
// inject preload/prefetch to HTML
webpackConfig
.plugin('preload')
.use(PreloadPlugin, [{
rel: 'preload',
include: 'initial',
fileBlacklist: [/\.map$/, /hot-update\.js$/]
}])
webpackConfig
.plugin('prefetch')
.use(PreloadPlugin, [{
rel: 'prefetch',
include: 'asyncChunks'
}])
}
} else {
// multi-page setup
webpackConfig.entryPoints.clear()
const pages = Object.keys(multiPageConfig)
const normalizePageConfig = c => typeof c === 'string' ? { entry: c } : c
pages.forEach(name => {
const pageConfig = normalizePageConfig(multiPageConfig[name])
const {
entry,
template = `public/${name}.html`,
filename = `${name}.html`,
chunks = ['chunk-vendors', 'chunk-common', name]
} = pageConfig
// Currently Cypress v3.1.0 comes with a very old version of Node,
// which does not support object rest syntax.
// (https://github.com/cypress-io/cypress/issues/2253)
// So here we have to extract the customHtmlOptions manually.
const customHtmlOptions = {}
for (const key in pageConfig) {
if (
!['entry', 'template', 'filename', 'chunks'].includes(key)
) {
customHtmlOptions[key] = pageConfig[key]
}
}
// inject entry
const entries = Array.isArray(entry) ? entry : [entry]
webpackConfig.entry(name).merge(entries.map(e => api.resolve(e)))
// trim inline loader
// * See https://github.com/jantimon/html-webpack-plugin/blob/master/docs/template-option.md#2-setting-a-loader-directly-for-the-template
const templateWithoutLoader = template.replace(/^.+!/, '').replace(/\?.+$/, '')
// resolve page index template
const hasDedicatedTemplate = fs.existsSync(api.resolve(templateWithoutLoader))
const templatePath = hasDedicatedTemplate
? template
: fs.existsSync(htmlPath)
? htmlPath
: defaultHtmlPath
publicCopyIgnore.push(api.resolve(templateWithoutLoader).replace(/\\/g, '/'))
// inject html plugin for the page
const pageHtmlOptions = Object.assign(
{},
htmlOptions,
{
chunks,
template: templatePath,
filename: ensureRelative(outputDir, filename)
},
customHtmlOptions
)
webpackConfig
.plugin(`html-${name}`)
.use(HTMLPlugin, [pageHtmlOptions])
})
if (!isLegacyBundle) {
pages.forEach(name => {
const filename = ensureRelative(
outputDir,
normalizePageConfig(multiPageConfig[name]).filename || `${name}.html`
)
webpackConfig
.plugin(`preload-${name}`)
.use(PreloadPlugin, [{
rel: 'preload',
includeHtmlNames: [filename],
include: {
type: 'initial',
entries: [name]
},
fileBlacklist: [/\.map$/, /hot-update\.js$/]
}])
webpackConfig
.plugin(`prefetch-${name}`)
.use(PreloadPlugin, [{
rel: 'prefetch',
includeHtmlNames: [filename],
include: {
type: 'asyncChunks',
entries: [name]
}
}])
})
}
}
// CORS and Subresource Integrity
if (options.crossorigin != null || options.integrity) {
webpackConfig
.plugin('cors')
.use(require('../webpack/CorsPlugin'), [{
crossorigin: options.crossorigin,
integrity: options.integrity,
publicPath: options.publicPath
}])
}
// copy static assets in public/
const publicDir = api.resolve('public')
if (!isLegacyBundle && fs.existsSync(publicDir)) {
webpackConfig
.plugin('copy')
.use(require('copy-webpack-plugin'), [{
patterns: [{
from: publicDir,
to: outputDir,
toType: 'dir',
globOptions: {
ignore: publicCopyIgnore
}
}]
}])
}
})
}