第一次使用Laravel 5.8 + Homestead构建PWA。当页面加载时,我会得到以下错误:
app.js:42706 Uncaught ReferenceError: window is not defined
ServiceWorker registration failed: TypeError: Failed to register a ServiceWorker: ServiceWorker script evaluation failed我的app.js中的错误行是:
window._ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");缓存的工作程序app.js无法解析window常量。
我已经设置了sw-precache-webpack-plugin,所以我的webpack.mix.js是:
const mix = require('laravel-mix');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
mix.js('resources/js/custom/buildings.js', 'public/js')
.js('resources/js/custom/home.js', 'public/js')
.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.options({
processCssUrls: false
})
.webpackConfig({
plugins: [
new SWPrecacheWebpackPlugin({
cacheId: 'sccpwa',
filename: 'service-worker.js',
staticFileGlobs: ['public/**/*.{css,eot,svg,ttf,woff,woff2,js,html}'],
minify: true,
stripPrefix: 'public/',
handleFetch: true,
dynamicUrlToDependencies: {
'/': ['resources/views/auth/login.blade.php'],
'/building/list': ['resources/views/pages/building.blade.php'],
'/home': ['resources/views/pages/home.blade.php'],
},
staticFileGlobsIgnorePatterns: [/\.map$/, /mix-manifest\.json$/, /manifest\.json$/, /service-worker\.js$/],
navigateFallback: '/',
runtimeCaching: [
{
urlPattern: /^https:\/\/fonts\.googleapis\.com\//,
handler: 'cacheFirst'
},
{
urlPattern: /^https:\/\/www\.projecturl\.com\/img\/(\w+)\.jpg/,
handler: 'cacheFirst'
}
],
importScripts: [
'./js/app.js',
'./js/buildings.js',
'./js/home.js'
]
})
]
});然后,我将它添加到在我的app.js顶部注册服务工作者。
require('./app-bootstrap');
if ('serviceWorker' in navigator ) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
$(document).ready(function() { .APP JS STUFF HERE. };npm编译它时没有任何错误,我可以看到addEventListener正在执行,但是上面的错误会弹出。
我错过了什么?谢谢!
发布于 2019-05-26 09:35:39
这个错误是一个非常简单的错误。您正在将应用程序代码导入(importScript)到SW脚本。当它试图执行时,会发生错误。
服务工作者执行上下文与通常的页面执行上下文不同。您不能在SW中执行1:1的应用程序代码。这通常都没有任何意义。
我基本上可以肯定,您理解了工作箱配置中的importScripts参数。它的意思是:将这些脚本导入SW并执行它们。
https://stackoverflow.com/questions/56310050
复制相似问题