app.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. // config that are specific to --target app
  2. const fs = require('fs')
  3. const path = require('path')
  4. // ensure the filename passed to html-webpack-plugin is a relative path
  5. // because it cannot correctly handle absolute paths
  6. function ensureRelative (outputDir, _path) {
  7. if (path.isAbsolute(_path)) {
  8. return path.relative(outputDir, _path)
  9. } else {
  10. return _path
  11. }
  12. }
  13. module.exports = (api, options) => {
  14. api.chainWebpack(webpackConfig => {
  15. // only apply when there's no alternative target
  16. if (process.env.VUE_CLI_BUILD_TARGET && process.env.VUE_CLI_BUILD_TARGET !== 'app') {
  17. return
  18. }
  19. const isProd = process.env.NODE_ENV === 'production'
  20. const isLegacyBundle = process.env.VUE_CLI_MODERN_MODE && !process.env.VUE_CLI_MODERN_BUILD
  21. const outputDir = api.resolve(options.outputDir)
  22. const getAssetPath = require('../util/getAssetPath')
  23. const outputFilename = getAssetPath(
  24. options,
  25. `js/[name]${isLegacyBundle ? `-legacy` : ``}${isProd && options.filenameHashing ? '.[contenthash:8]' : ''}.js`
  26. )
  27. webpackConfig
  28. .output
  29. .filename(outputFilename)
  30. .chunkFilename(outputFilename)
  31. // code splitting
  32. if (process.env.NODE_ENV !== 'test') {
  33. webpackConfig
  34. .optimization.splitChunks({
  35. cacheGroups: {
  36. vendors: {
  37. name: `chunk-vendors`,
  38. test: /[\\/]node_modules[\\/]/,
  39. priority: -10,
  40. chunks: 'initial'
  41. },
  42. common: {
  43. name: `chunk-common`,
  44. minChunks: 2,
  45. priority: -20,
  46. chunks: 'initial',
  47. reuseExistingChunk: true
  48. }
  49. }
  50. })
  51. }
  52. // HTML plugin
  53. const resolveClientEnv = require('../util/resolveClientEnv')
  54. // #1669 html-webpack-plugin's default sort uses toposort which cannot
  55. // handle cyclic deps in certain cases. Monkey patch it to handle the case
  56. // before we can upgrade to its 4.0 version (incompatible with preload atm)
  57. const chunkSorters = require('html-webpack-plugin/lib/chunksorter')
  58. const depSort = chunkSorters.dependency
  59. chunkSorters.auto = chunkSorters.dependency = (chunks, ...args) => {
  60. try {
  61. return depSort(chunks, ...args)
  62. } catch (e) {
  63. // fallback to a manual sort if that happens...
  64. return chunks.sort((a, b) => {
  65. // make sure user entry is loaded last so user CSS can override
  66. // vendor CSS
  67. if (a.id === 'app') {
  68. return 1
  69. } else if (b.id === 'app') {
  70. return -1
  71. } else if (a.entry !== b.entry) {
  72. return b.entry ? -1 : 1
  73. }
  74. return 0
  75. })
  76. }
  77. }
  78. const htmlOptions = {
  79. title: api.service.pkg.name,
  80. templateParameters: (compilation, assets, pluginOptions) => {
  81. // enhance html-webpack-plugin's built in template params
  82. let stats
  83. return Object.assign({
  84. // make stats lazy as it is expensive
  85. get webpack () {
  86. return stats || (stats = compilation.getStats().toJson())
  87. },
  88. compilation: compilation,
  89. webpackConfig: compilation.options,
  90. htmlWebpackPlugin: {
  91. files: assets,
  92. options: pluginOptions
  93. }
  94. }, resolveClientEnv(options, true /* raw */))
  95. }
  96. }
  97. // handle indexPath
  98. if (options.indexPath !== 'index.html') {
  99. // why not set filename for html-webpack-plugin?
  100. // 1. It cannot handle absolute paths
  101. // 2. Relative paths causes incorrect SW manifest to be generated (#2007)
  102. webpackConfig
  103. .plugin('move-index')
  104. .use(require('../webpack/MovePlugin'), [
  105. path.resolve(outputDir, 'index.html'),
  106. path.resolve(outputDir, options.indexPath)
  107. ])
  108. }
  109. if (isProd) {
  110. Object.assign(htmlOptions, {
  111. minify: {
  112. removeComments: true,
  113. collapseWhitespace: true,
  114. collapseBooleanAttributes: true,
  115. removeScriptTypeAttributes: true
  116. // more options:
  117. // https://github.com/kangax/html-minifier#options-quick-reference
  118. }
  119. })
  120. // keep chunk ids stable so async chunks have consistent hash (#1916)
  121. webpackConfig
  122. .plugin('named-chunks')
  123. .use(require('webpack/lib/NamedChunksPlugin'), [chunk => {
  124. if (chunk.name) {
  125. return chunk.name
  126. }
  127. const hash = require('hash-sum')
  128. const joinedHash = hash(
  129. Array.from(chunk.modulesIterable, m => m.id).join('_')
  130. )
  131. return `chunk-` + joinedHash
  132. }])
  133. }
  134. // resolve HTML file(s)
  135. const HTMLPlugin = require('html-webpack-plugin')
  136. const PreloadPlugin = require('@vue/preload-webpack-plugin')
  137. const multiPageConfig = options.pages
  138. const htmlPath = api.resolve('public/index.html')
  139. const defaultHtmlPath = path.resolve(__dirname, 'index-default.html')
  140. const publicCopyIgnore = ['.DS_Store']
  141. if (!multiPageConfig) {
  142. // default, single page setup.
  143. htmlOptions.template = fs.existsSync(htmlPath)
  144. ? htmlPath
  145. : defaultHtmlPath
  146. publicCopyIgnore.push({
  147. glob: path.relative(api.resolve('public'), api.resolve(htmlOptions.template)),
  148. matchBase: false
  149. })
  150. webpackConfig
  151. .plugin('html')
  152. .use(HTMLPlugin, [htmlOptions])
  153. if (!isLegacyBundle) {
  154. // inject preload/prefetch to HTML
  155. webpackConfig
  156. .plugin('preload')
  157. .use(PreloadPlugin, [{
  158. rel: 'preload',
  159. include: 'initial',
  160. fileBlacklist: [/\.map$/, /hot-update\.js$/]
  161. }])
  162. webpackConfig
  163. .plugin('prefetch')
  164. .use(PreloadPlugin, [{
  165. rel: 'prefetch',
  166. include: 'asyncChunks'
  167. }])
  168. }
  169. } else {
  170. // multi-page setup
  171. webpackConfig.entryPoints.clear()
  172. const pages = Object.keys(multiPageConfig)
  173. const normalizePageConfig = c => typeof c === 'string' ? { entry: c } : c
  174. pages.forEach(name => {
  175. const pageConfig = normalizePageConfig(multiPageConfig[name])
  176. const {
  177. entry,
  178. template = `public/${name}.html`,
  179. filename = `${name}.html`,
  180. chunks = ['chunk-vendors', 'chunk-common', name]
  181. } = pageConfig
  182. // Currently Cypress v3.1.0 comes with a very old version of Node,
  183. // which does not support object rest syntax.
  184. // (https://github.com/cypress-io/cypress/issues/2253)
  185. // So here we have to extract the customHtmlOptions manually.
  186. const customHtmlOptions = {}
  187. for (const key in pageConfig) {
  188. if (
  189. !['entry', 'template', 'filename', 'chunks'].includes(key)
  190. ) {
  191. customHtmlOptions[key] = pageConfig[key]
  192. }
  193. }
  194. // inject entry
  195. const entries = Array.isArray(entry) ? entry : [entry]
  196. webpackConfig.entry(name).merge(entries.map(e => api.resolve(e)))
  197. // resolve page index template
  198. const hasDedicatedTemplate = fs.existsSync(api.resolve(template))
  199. const templatePath = hasDedicatedTemplate
  200. ? template
  201. : fs.existsSync(htmlPath)
  202. ? htmlPath
  203. : defaultHtmlPath
  204. publicCopyIgnore.push({
  205. glob: path.relative(api.resolve('public'), api.resolve(templatePath)),
  206. matchBase: false
  207. })
  208. // inject html plugin for the page
  209. const pageHtmlOptions = Object.assign(
  210. {},
  211. htmlOptions,
  212. {
  213. chunks,
  214. template: templatePath,
  215. filename: ensureRelative(outputDir, filename)
  216. },
  217. customHtmlOptions
  218. )
  219. webpackConfig
  220. .plugin(`html-${name}`)
  221. .use(HTMLPlugin, [pageHtmlOptions])
  222. })
  223. if (!isLegacyBundle) {
  224. pages.forEach(name => {
  225. const filename = ensureRelative(
  226. outputDir,
  227. normalizePageConfig(multiPageConfig[name]).filename || `${name}.html`
  228. )
  229. webpackConfig
  230. .plugin(`preload-${name}`)
  231. .use(PreloadPlugin, [{
  232. rel: 'preload',
  233. includeHtmlNames: [filename],
  234. include: {
  235. type: 'initial',
  236. entries: [name]
  237. },
  238. fileBlacklist: [/\.map$/, /hot-update\.js$/]
  239. }])
  240. webpackConfig
  241. .plugin(`prefetch-${name}`)
  242. .use(PreloadPlugin, [{
  243. rel: 'prefetch',
  244. includeHtmlNames: [filename],
  245. include: {
  246. type: 'asyncChunks',
  247. entries: [name]
  248. }
  249. }])
  250. })
  251. }
  252. }
  253. // CORS and Subresource Integrity
  254. if (options.crossorigin != null || options.integrity) {
  255. webpackConfig
  256. .plugin('cors')
  257. .use(require('../webpack/CorsPlugin'), [{
  258. crossorigin: options.crossorigin,
  259. integrity: options.integrity,
  260. publicPath: options.publicPath
  261. }])
  262. }
  263. // copy static assets in public/
  264. const publicDir = api.resolve('public')
  265. if (!isLegacyBundle && fs.existsSync(publicDir)) {
  266. webpackConfig
  267. .plugin('copy')
  268. .use(require('copy-webpack-plugin'), [[{
  269. from: publicDir,
  270. to: outputDir,
  271. toType: 'dir',
  272. ignore: publicCopyIgnore
  273. }]])
  274. }
  275. })
  276. }