mirror of
https://github.com/vuejs/vue-cli.git
synced 2026-04-24 05:50:21 -05:00
tweak pwa registration script
This commit is contained in:
@@ -3,6 +3,7 @@ module.exports = {
|
||||
parserOptions: {
|
||||
parser: require.resolve('babel-eslint')
|
||||
},
|
||||
globals: ['process'],
|
||||
rules: {
|
||||
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
|
||||
}
|
||||
|
||||
@@ -60,8 +60,8 @@ test('pwa', async () => {
|
||||
|
||||
await new Promise(r => setTimeout(r, 500))
|
||||
const logs = launched.logs
|
||||
expect(logs.some(msg => msg.match(/Content is cached for offline use/))).toBe(true)
|
||||
expect(logs.some(msg => msg.match(/This web app is being served cache-first/))).toBe(true)
|
||||
expect(logs.some(msg => msg.match(/Content has been cached for offline use/))).toBe(true)
|
||||
expect(logs.some(msg => msg.match(/App is being served from cache by a service worker/))).toBe(true)
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
module.exports = api => {
|
||||
api.extendPackage({
|
||||
dependencies: {
|
||||
'register-service-worker': '^1.0.0'
|
||||
}
|
||||
})
|
||||
|
||||
api.render('./template')
|
||||
|
||||
api.postProcessFiles(files => {
|
||||
|
||||
@@ -1,23 +1,26 @@
|
||||
/* eslint-disable no-console */
|
||||
|
||||
import { register } from '@vue/cli-plugin-pwa/registerServiceWorker'
|
||||
import { register } from 'register-service-worker'
|
||||
|
||||
const serviceWorkerEventBus = register()
|
||||
|
||||
serviceWorkerEventBus.$on('new-content', () => {
|
||||
console.log('New content is available; please refresh.')
|
||||
})
|
||||
|
||||
serviceWorkerEventBus.$on('content-cached', () => {
|
||||
console.log('Content is cached for offline use.')
|
||||
})
|
||||
|
||||
serviceWorkerEventBus.$on('offline', () => {
|
||||
console.log('No internet connection found. App is running in offline mode.')
|
||||
})
|
||||
|
||||
serviceWorkerEventBus.$on('error', error => {
|
||||
console.error('Error during service worker registration:', error)
|
||||
})
|
||||
|
||||
export default serviceWorkerEventBus
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
register(`${process.env.BASE_URL}service-worker.js`, {
|
||||
ready () {
|
||||
console.log(
|
||||
'App is being served from cache by a service worker.\n' +
|
||||
'For more details, visit https://goo.gl/M232X8'
|
||||
)
|
||||
},
|
||||
cached () {
|
||||
console.log('Content has been cached for offline use.')
|
||||
},
|
||||
updated () {
|
||||
console.log('New content is available; please refresh.')
|
||||
},
|
||||
offline () {
|
||||
console.log('No internet connection found. App is running in offline mode.')
|
||||
},
|
||||
error (error) {
|
||||
console.error('Error during service worker registration:', error)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2,12 +2,6 @@ module.exports = (api, options) => {
|
||||
api.chainWebpack(webpackConfig => {
|
||||
const name = api.service.pkg.name
|
||||
|
||||
// make sure the registerServiceWorker script is transpiled
|
||||
webpackConfig.module
|
||||
.rule('js')
|
||||
.include
|
||||
.add(require.resolve('./registerServiceWorker'))
|
||||
|
||||
// the pwa plugin hooks on to html-webpack-plugin
|
||||
// and injects icons, manifest links & other PWA related tags into <head>
|
||||
webpackConfig
|
||||
|
||||
@@ -23,5 +23,8 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"sw-precache-webpack-plugin": "^0.11.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"register-service-worker": "^1.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
/* global fetch, URL */
|
||||
|
||||
// In production, we register a service worker to serve assets from local cache.
|
||||
|
||||
// This lets the app load faster on subsequent visits in production, and gives
|
||||
// it offline capabilities. However, it also means that developers (and users)
|
||||
// will only see deployed updates on the "N+1" visit to a page, since previously
|
||||
// cached resources are updated in the background.
|
||||
|
||||
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
|
||||
// This link also includes instructions on opting out of this behavior.
|
||||
|
||||
const isLocalhost = Boolean(
|
||||
window.location.hostname === 'localhost' ||
|
||||
// [::1] is the IPv6 localhost address.
|
||||
window.location.hostname === '[::1]' ||
|
||||
// 127.0.0.1/8 is considered localhost for IPv4.
|
||||
window.location.hostname.match(
|
||||
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
|
||||
)
|
||||
)
|
||||
|
||||
import Vue from 'vue'
|
||||
|
||||
export function register () {
|
||||
const emitter = new Vue()
|
||||
|
||||
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
|
||||
// The URL constructor is available in all browsers that support SW.
|
||||
const publicUrl = new URL(process.env.PUBLIC_URL, window.location)
|
||||
if (publicUrl.origin !== window.location.origin) {
|
||||
// Our service worker won't work if PUBLIC_URL is on a different origin
|
||||
// from what our page is served on. This might happen if a CDN is used to
|
||||
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
|
||||
return emitter
|
||||
}
|
||||
|
||||
window.addEventListener('load', () => {
|
||||
const swUrl = `${process.env.PUBLIC_URL}service-worker.js`
|
||||
|
||||
if (isLocalhost) {
|
||||
// This is running on localhost. Lets check if a service worker still exists or not.
|
||||
checkValidServiceWorker(swUrl, emitter)
|
||||
|
||||
// Add some additional logging to localhost, pointing developers to the
|
||||
// service worker/PWA documentation.
|
||||
navigator.serviceWorker.ready.then(() => {
|
||||
console.log(
|
||||
'This web app is being served cache-first by a service ' +
|
||||
'worker. To learn more, visit https://goo.gl/M232X8'
|
||||
)
|
||||
})
|
||||
} else {
|
||||
// Is not local host. Just register service worker
|
||||
registerValidSW(swUrl, emitter)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return emitter
|
||||
}
|
||||
|
||||
function registerValidSW (swUrl, emitter) {
|
||||
navigator.serviceWorker
|
||||
.register(swUrl)
|
||||
.then(registration => {
|
||||
registration.onupdatefound = () => {
|
||||
const installingWorker = registration.installing
|
||||
installingWorker.onstatechange = () => {
|
||||
if (installingWorker.state === 'installed') {
|
||||
if (navigator.serviceWorker.controller) {
|
||||
// At this point, the old content will have been purged and
|
||||
// the fresh content will have been added to the cache.
|
||||
// It's the perfect time to display a "New content is
|
||||
// available; please refresh." message in your web app.
|
||||
emitter.$emit('new-content')
|
||||
} else {
|
||||
// At this point, everything has been precached.
|
||||
// It's the perfect time to display a
|
||||
// "Content is cached for offline use." message.
|
||||
emitter.$emit('content-cached')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
emitter.$emit('error', error)
|
||||
})
|
||||
}
|
||||
|
||||
function checkValidServiceWorker (swUrl, emitter) {
|
||||
// Check if the service worker can be found. If it can't reload the page.
|
||||
fetch(swUrl)
|
||||
.then(response => {
|
||||
// Ensure service worker exists, and that we really are getting a JS file.
|
||||
if (
|
||||
response.status === 404 ||
|
||||
response.headers.get('content-type').indexOf('javascript') === -1
|
||||
) {
|
||||
// No service worker found. Probably a different app. Reload the page.
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister().then(() => {
|
||||
window.location.reload()
|
||||
})
|
||||
})
|
||||
} else {
|
||||
// Service worker found. Proceed as normal.
|
||||
registerValidSW(swUrl, emitter)
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
emitter.$emit('offline')
|
||||
})
|
||||
}
|
||||
|
||||
export function unregister () {
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister()
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,7 @@ module.exports = (api, options) => {
|
||||
|
||||
if (!args.silent) {
|
||||
done(`Build complete. The ${chalk.cyan(options.outputDir)} directory is ready to be deployed.\n`)
|
||||
if (options.base === '/') {
|
||||
if (options.baseUrl === '/') {
|
||||
info(`The app is built assuming that it will be deployed at the root of a domain.`)
|
||||
info(`If you intend to deploy it under a subpath, update the ${chalk.green('base')} option`)
|
||||
info(`in your project config (${chalk.cyan(`vue.config.js`)} or ${chalk.green('"vue"')} field in ${chalk.cyan(`package.json`)}).\n`)
|
||||
|
||||
@@ -11,7 +11,7 @@ module.exports = (api, options) => {
|
||||
.output
|
||||
.path(api.resolve(options.outputDir))
|
||||
.filename('[name].js')
|
||||
.publicPath(options.base)
|
||||
.publicPath(options.baseUrl)
|
||||
|
||||
webpackConfig.resolve
|
||||
.set('symlinks', true)
|
||||
@@ -123,7 +123,9 @@ module.exports = (api, options) => {
|
||||
|
||||
webpackConfig
|
||||
.plugin('define')
|
||||
.use(require('webpack/lib/DefinePlugin'), [resolveClientEnv(options.base)])
|
||||
.use(require('webpack/lib/DefinePlugin'), [
|
||||
resolveClientEnv(options.baseUrl)
|
||||
])
|
||||
|
||||
webpackConfig
|
||||
.plugin('timefix')
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
const { createSchema, validate } = require('@vue/cli-shared-utils')
|
||||
|
||||
const schema = createSchema(joi => joi.object({
|
||||
base: joi.string(),
|
||||
baseUrl: joi.string(),
|
||||
outputDir: joi.string(),
|
||||
compiler: joi.boolean(),
|
||||
cssModules: joi.boolean(),
|
||||
@@ -25,7 +25,7 @@ exports.validate = options => validate(
|
||||
|
||||
exports.defaults = {
|
||||
// project deployment base
|
||||
base: '/',
|
||||
baseUrl: '/',
|
||||
|
||||
// where to output built files
|
||||
outputDir: 'dist',
|
||||
|
||||
@@ -7,7 +7,7 @@ module.exports = function resolveClientEnv (publicPath) {
|
||||
env[key] = JSON.stringify(process.env[key])
|
||||
}
|
||||
})
|
||||
env.PUBLIC_URL = JSON.stringify(publicPath)
|
||||
env.BASE_URL = JSON.stringify(publicPath)
|
||||
return {
|
||||
'process.env': env
|
||||
}
|
||||
|
||||
+6
-1
@@ -27,7 +27,8 @@ const packagesToCheck = [
|
||||
'less',
|
||||
'less-loader',
|
||||
'stylus',
|
||||
'stylus-loader'
|
||||
'stylus-loader',
|
||||
'register-service-worker'
|
||||
]
|
||||
const npmPackageRE = new RegExp(`'(${packagesToCheck.join('|')})': '\\^(\\d+\\.\\d+\\.\\d+[^']*)'`)
|
||||
|
||||
@@ -126,6 +127,10 @@ const flushWrite = () => {
|
||||
}
|
||||
}))
|
||||
|
||||
if (!Object.keys(writeCache).length) {
|
||||
return console.log(`All packages up-to-date.`)
|
||||
}
|
||||
|
||||
const { yes } = await inquirer.prompt([{
|
||||
name: 'yes',
|
||||
type: 'confirm',
|
||||
|
||||
@@ -7826,6 +7826,10 @@ regexpu-core@^4.1.3:
|
||||
unicode-match-property-ecmascript "^1.0.3"
|
||||
unicode-match-property-value-ecmascript "^1.0.1"
|
||||
|
||||
register-service-worker@^1.0.0:
|
||||
version "1.0.0"
|
||||
resolved "https://registry.yarnpkg.com/register-service-worker/-/register-service-worker-1.0.0.tgz#c1a44e3fd1bd14e7cd8d36b3d86c8c4711e23ee4"
|
||||
|
||||
registry-auth-token@^3.0.1:
|
||||
version "3.3.1"
|
||||
resolved "https://registry.yarnpkg.com/registry-auth-token/-/registry-auth-token-3.3.1.tgz#fb0d3289ee0d9ada2cbb52af5dfe66cb070d3006"
|
||||
|
||||
Reference in New Issue
Block a user