app.js 8.9 KB

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