Giter VIP home page Giter VIP logo

laravel-mix-workbox's Introduction

Laravel Mix Workbox

This extension provides instant Workbox support to your Mix (v4.0 and up) builds.

Usage

First, install the extension.

npm install laravel-mix-workbox --save-dev

Then, require it within your webpack.mix.js file, like so:

// webpack.mix.js

let mix = require('laravel-mix');

require('laravel-mix-workbox');

mix
    .js('resources/js/app.js', 'public/js')
    .less('resources/less/app.less', 'public/css')
    .generateSW();

And you're done! Compile everything down with npm run dev.

By default the service worker file will be generated in the public/ folder ad will be set up to precache all the files in your webpack build.

In your web page, you can register this service worker by adding:

<script>
// Check that service workers are supported
if ('serviceWorker' in navigator) {
  // Use the window load event to keep the page load performant
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/service-worker.js');
  });
}
</script>

or using workbox-window module:

// e.g. app.js

import {Workbox} from 'workbox-window';

if ('serviceWorker' in navigator) {
  const wb = new Workbox('/service-worker.js');

  wb.register();
}

You can pass in additional configuration like so:

// webpack.mix.js

let mix = require('laravel-mix');

require('laravel-mix-workbox');

mix
    .js('resources/js/app.js', 'public/js')
    .less('resources/less/app.less', 'public/css')
    .generateSW({
        // Do not precache images
        exclude: [/\.(?:png|jpg|jpeg|svg)$/],

        // Define runtime caching rules.
        runtimeCaching: [{
            // Match any request that ends with .png, .jpg, .jpeg or .svg.
            urlPattern: /\.(?:png|jpg|jpeg|svg)$/,

            // Apply a cache-first strategy.
            handler: 'CacheFirst',

            options: {
                // Use a custom cache name.
                cacheName: 'images',

                // Only cache 10 images.
                expiration: {
                    maxEntries: 10,
                },
            },
        }],

        skipWaiting: true
    });

The full set of available options can be found on the Workbox Webpack module page.

InjectManifest

You can also use the InjectManifest plugin like so:

// resources/js/service-worker.js

import { precacheAndRoute } from 'workbox-precaching';

precacheAndRoute(self.__WB_MANIFEST || []);
// webpack.mix.js

let mix = require('laravel-mix');

require('laravel-mix-workbox');

mix
    .js('resources/js/app.js', 'public/js')
    .less('resources/less/app.less', 'public/css')
    .injectManifest({
      swSrc: './resources/js/service-worker.js'
    });

This will create a precache manifest (a list of webpack assets) and inject it into your service worker file via importScripts().

You can pass the appropriate configuration as properties of an Object.

A full set of configuration options can be found on this reference page.

laravel-mix-workbox's People

Contributors

devbapidey avatar speniti avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

laravel-mix-workbox's Issues

Webpack compiling in production with workbox

Hi!

I am looking for some guidance on how to use laravel-mix-workbox for deployment in production environnement, while running npm run production on the production server or CD. I had issues in the past where I had loading chuck failed error.

What files should I ignore or keep ?

Thanks!

Wrong route for css and js

After compiling, the manifest line looks like this:

Object(workbox_precaching_precacheAndRoute__WEBPACK_IMPORTED_MODULE_1__["precacheAndRoute"])([{'revision':'7cab58508017b184d0f25707188bcee0','url':'//css/app.css'},{'revision':'5708fbfc3cf0f5992f08a6d48d898f87','url':'//js/app.js'}]);

The problem is the double slash before the css and js folders, it throws an error saying failed to fetch:

error (4)

PS: before I used the workbox plugin for webpack, but it was the same

Static assets are not included in precache manifest

When static assets are added to the build process either via the copyDirectory function or via the copy-webpack-plugin, those files are not added to the precache manifest.

This webpack.mix.js does not include the static assets:

const mix = require('laravel-mix');

//mp035 add workbox plugin and copy-webpack-plugin
require('laravel-mix-workbox');
const CopyPlugin = require('copy-webpack-plugin');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

//mp035 fix issue with laravel-mix outputting bad urls in precache manifest for app.js (//js/app.js) and app.css
// and copy assets into place (so they are in the build tree)
mix.webpackConfig({
    output: {
      publicPath: ''
    },
    plugins: [
        new CopyPlugin([
          { from: 'resources/img/*', to: 'public/img', flatten:true },
          { from: 'resources/root/*', to: 'public', flatten:true },
        ]),
      ],
  })


.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css')
   .sourceMaps().version()

// mp035 add inject manifest plugin to inject workbox manifest into the service worker.
.injectManifest({
    swSrc: './resources/pwa/service-worker.js',
    maximumFileSizeToCacheInBytes: 20000000, // ******************************DEBUG ONLY!!!
});

However this one works fine (using the standard workbox-webpack plugin):

const mix = require('laravel-mix');

//mp035 add workbox plugin and copy-webpack-plugin
const CopyPlugin = require('copy-webpack-plugin');
const {InjectManifest} = require('workbox-webpack-plugin');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

//mp035 fix issue with laravel-mix outputting bad urls in precache manifest for app.js (//js/app.js) and app.css
// and copy assets into place (so they are in the build tree)
mix.webpackConfig({
    output: {
      publicPath: ''
    },
    plugins: [
        new CopyPlugin([
          { from: 'resources/img/*', to: 'public/img', flatten:true },
          { from: 'resources/root/*', to: 'public', flatten:true },
        ]),
        new InjectManifest({
            swSrc: './resources/pwa/service-worker.js',
            maximumFileSizeToCacheInBytes: 20000000, // ******************************DEBUG ONLY!!!
        }),
      ],
  })


.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css')
   .sourceMaps().version();

Double slash in url to resources

Hi, thanks for the extension. Help me understand why when generating the public / service-worker.js file in the url field, two //?
Object(workbox_precaching__WEBPACK_IMPORTED_MODULE_0__["precacheAndRoute"])([{'revision':'06df4f4173949b061ade3ae814fb9cc0','url':'//assets/css/app.css'},{'revision':'740fd697b8866b74cd7b8f669ddfbe6f','url':'//assets/css/styles.css'},{'revision':'21bae4ecf78d79fd154031c710bdc3a1','url':'//js/app.js'},{'revision':'af92f221c524c24ee9b3ee3f8f9ccb5b','url':'//js/manifest.js'},{'revision':'d00b83cc3284f2145135d02953b02f38','url':'//js/vendor.js'}] || []);

No mix v6.* support?

Describe the bug
I cannot run production command using laravel-mix 6.*

To Reproduce
Just try to run production script using the most recent laravel-mix (and webpack) package.

Desktop (please complete the following information):

  • OS: Windows 10

Additional context

> mix --production

        Additional dependencies must be installed. This will only take a moment.
 
        Running: npm install workbox-webpack-plugin --save-dev --legacy-peer-deps
 
npm WARN deprecated @hapi/[email protected]: Switch to 'npm install joi'
npm WARN deprecated @hapi/[email protected]: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated @hapi/[email protected]: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated @hapi/[email protected]: Moved to 'npm install @sideway/address'
npm WARN deprecated @hapi/[email protected]: Moved to 'npm install @sideway/formula'
npm WARN deprecated @hapi/[email protected]: Moved to 'npm install @sideway/pinpoint'
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\@types\browser-sync\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"
os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"o
s":"win32","arch":"x64"})

        Finished. Please run Mix again.
 
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] production: `mix --production`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] production script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\twent\AppData\Roaming\npm-cache\_logs\2021-06-13T13_26_34_112Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] prod: `npm run production`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] prod script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\twent\AppData\Roaming\npm-cache\_logs\2021-06-13T13_26_34_128Z-debug.log

Broken async chunk URLs from resetting public path

Describe the bug
Starting in v0.1.3, this plugin resets the publicPath config key to solve an issue with duplicate slashes. However, this will break loading async chunks in projects that define a custom publicPath and which don't load their assets from the root / but some subfolder like /dist/assets/.

Expected behavior
The plugin shouldn't modify any previously set publicPath.

Suggested fix
I've previously fixed the double-slash issue by adding a manifest transform. Maybe adding this as a default transform makes resetting the public path unnecessary. OTOH, you'd need to be smart about merging the default transform with any user-supplied transform array.

const fixDoubleSlashes = (manifestEntries) => {
  const manifest = manifestEntries.map(entry => {
    entry.url = entry.url.replace('//', '/')
    return entry
  })
  return { manifest, warnings: [] }
}

mix.generateSW({
  manifestTransforms: [fixDoubleSlashes]
})

Configure maximumFileSizeToCacheInBytes to change this limit

Hi,

Can you please help with using plugin. I am trying to use maximumFileSizeToCacheInBytes option for generateSW method. Unfortunately it did not work https://prnt.sc/snfgi4

Does your plugin support maximumFileSizeToCacheInBytes? I found that option supports for injectManifest but I would like to use fully automated mode without writing SW file by myself :)

Thanks, in advice

Offline page?

Chrome Dev Tools

Site cannot be installed: Page does not work offline. Starting in Chrome 93, the installability criteria is changing, and this site will not be installable. See https://goo.gle/improved-pwa-offline-detection for more information.

Question
What is the correct way to make PWA to work offline with the package?

For example in silviolleite/laravelpwa is like this:

self.addEventListener("fetch", event => {
    event.respondWith(
        caches.match(event.request)
            .then(response => {
                return response || fetch(event.request);
            })
            .catch(() => {
                return caches.match('offline');
            })
    )
});

npm run prod not working

I am not sure what is wrong but when I do npm run dev it compiles and it works but when I try with npm run prod I get the following errors:

-bash-4.2$ npm run prod

> prod
> npm run production


> production
> mix --production


● Mix █████████████████████████ sealing (92%) asset processing
 RealContentHashPlugin

node:events:491
      throw er; // Unhandled 'error' event
      ^

Error: spawn /home/xxxxxxxxxx/.nvm/versions/node/v16.19.0/bin/node EAGAIN
    at Process.ChildProcess._handle.onexit (node:internal/child_process:285:19)
    at onErrorNT (node:internal/child_process:485:16)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
Emitted 'error' event on ChildProcess instance at:
    at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12)
    at onErrorNT (node:internal/child_process:485:16)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  errno: -11,
  code: 'EAGAIN',
  syscall: 'spawn /home/xxxxxxxxxx/.nvm/versions/node/v16.19.0/bin/node',
  path: '/home/xxxxxxxxxx/.nvm/versions/node/v16.19.0/bin/node',
  spawnargs: [
    '/home/xxxxxxxxxx/domains/grupocengall.com/public_html/node_modules/rollup-plugin-terser/node_modules/jest-worker/build/workers/processChild.js'
  ]
}
-bash-4.2$

My webpack.mix.js is:

const mix = require('laravel-mix');

require('laravel-mix-workbox');
/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel applications. By default, we are compiling the CSS
 | file for the application as well as bundling up all the JS files.
 |
 */

mix
    .js('resources/js/app.js', 'public/js')
    .sass('resources/scss/app.scss', 'public/css')
    .webpackConfig({
        output: {
            publicPath: ''
        }
    })
    .generateSW({
        exclude: [
            'mix.js'
        ],
        runtimeCaching: [{
            urlPattern: /\.(?:png|jpg|jpeg|svg|webp)$/,
            handler: 'CacheFirst',
            
        }],
        clientsClaim: true,
        skipWaiting: true
        
    })
    .sourceMaps(false);

if (mix.inProduction()) {
    mix.version();
}

If I delete the generateSW section then it can successfully complete the process so there might be a parameter I am missing. Can anyone help me?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.