index.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. const fs = require('fs')
  2. const { chalk, warn } = require('@vue/cli-shared-utils')
  3. module.exports = (api, options) => {
  4. const userOptions = options.pwa || {}
  5. const manifestPath = api.resolve('public/manifest.json')
  6. if (fs.existsSync(manifestPath)) {
  7. if (!userOptions.manifestOptions) {
  8. userOptions.manifestOptions = require(manifestPath)
  9. } else {
  10. warn(
  11. `The ${chalk.red('public/manifest.json')} file will be ignored in favor of ${chalk.cyan('pwa.manifestOptions')}`
  12. )
  13. }
  14. }
  15. api.chainWebpack(webpackConfig => {
  16. const target = process.env.VUE_CLI_BUILD_TARGET
  17. if (target && target !== 'app') {
  18. return
  19. }
  20. const name = api.service.pkg.name
  21. // the pwa plugin hooks on to html-webpack-plugin
  22. // and injects icons, manifest links & other PWA related tags into <head>
  23. webpackConfig
  24. .plugin('pwa')
  25. .use(require('./lib/HtmlPwaPlugin'), [Object.assign({
  26. name
  27. }, userOptions)])
  28. .after('html')
  29. // generate /service-worker.js in production mode
  30. if (process.env.NODE_ENV === 'production') {
  31. // Default to GenerateSW mode, though InjectManifest also might be used.
  32. const workboxPluginMode = userOptions.workboxPluginMode || 'GenerateSW'
  33. const workboxWebpackModule = require('workbox-webpack-plugin')
  34. if (!(workboxPluginMode in workboxWebpackModule)) {
  35. throw new Error(
  36. `${workboxPluginMode} is not a supported Workbox webpack plugin mode. ` +
  37. `Valid modes are: ${Object.keys(workboxWebpackModule).join(', ')}`
  38. )
  39. }
  40. const defaultOptions = {
  41. exclude: [
  42. /\.map$/,
  43. /img\/icons\//,
  44. /favicon\.ico$/,
  45. /^manifest.*\.js?$/
  46. ]
  47. }
  48. const defaultGenerateSWOptions = workboxPluginMode === 'GenerateSW' ? {
  49. cacheId: name
  50. } : {}
  51. const workBoxConfig = Object.assign(defaultOptions, defaultGenerateSWOptions, userOptions.workboxOptions)
  52. webpackConfig
  53. .plugin('workbox')
  54. .use(workboxWebpackModule[workboxPluginMode], [workBoxConfig])
  55. }
  56. })
  57. // install dev server middleware for resetting service worker during dev
  58. const createNoopServiceWorkerMiddleware = require('./lib/noopServiceWorkerMiddleware')
  59. api.configureDevServer(app => {
  60. app.use(createNoopServiceWorkerMiddleware())
  61. })
  62. }