E
E
Evgeny Khripunov2018-09-17 12:29:18
Web development
Evgeny Khripunov, 2018-09-17 12:29:18

How to include Service Worker along with webpack.mix version control in laravel?

There is a SPA application on laravel + vue.js. Using webpack mix, the application is assembled into the app.js file, and then the hash for the file is calculated using mix.version().

<!doctype html>
<html lang="ru">
<head>
   ...
    <link href="{{ mix('/css/app.css') }}" rel="stylesheet">   
    ...
</head>
<body id="body">
<div id="app"> 
</div>
<script>
    if ('serviceWorker' in navigator) {
        window.addEventListener('load', function () {
            navigator.serviceWorker.register('/service-worker.js').then(function (registration) {                
                console.log('ServiceWorker registration successful with scope: ', registration.scope);
            }, function (err) {                
                console.log('ServiceWorker registration failed: ', err);
            });
        });
    }
</script>
<script src="{{ mix('/js/app.js') }}"></script> //Тут подключается файл
</body>
</html>

Accordingly, when loading a file, a request is made for a file of the form 127.0.0.1:8000/js/app.js?id=19f8a0d604af0bbbce31
The webpack.mix.js file:
mix.webpackConfig({
    plugins: [
        new BundleAnalyzerPlugin(),
        new SWPrecacheWebpackPlugin({
            cacheId: 'pwa',
            filename: 'service-worker.js',
            staticFileGlobs: ['public/**/*.{css,eot,svg,ttf,woff,woff2,js,html,mp3}'],
            minify: true,
            stripPrefix: 'public/',
            handleFetch: true,
            dynamicUrlToDependencies: { 
                '/': ['resources/views/spa.blade.php'],                
            },
            staticFileGlobsIgnorePatterns: [/\.map$/, /mix-manifest\.json$/, /manifest\.json$/, /service-worker\.js$/],
            navigateFallback: '/',
            runtimeCaching: [
                {
                    urlPattern: /^https:\/\/fonts\.googleapis\.com\//,
                    handler: 'cacheFirst'
                },
                {
                    urlPattern: /^https:\/\/www\.thecocktaildb\.com\/images\/media\/drink\/(\w+)\.jpg/,
                    handler: 'cacheFirst'
                }
            ],
        })
    ],
    output: {publicPath: "/", chunkFilename: "js/[name]-[hash].js"}
});

With this line staticFileGlobs: ['public/**/*.{css,eot,svg,ttf,woff,woff2,js,html,mp3}'], the service worker caches all files. However, the app.js file is still stored with this name, but is requested via mix('/js/app.js') already with a cache. Therefore, when accessed from offline, the service worker for the app.js file does not work.
How can this be fixed?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question