Search code examples
reactjswebpackservice-workerprogressive-web-appsworkbox-webpack-plugin

workbox webpack 4 plugin unable to precache non-webpack assets


I am looking to precache images for a PWA, using this documentation.

I have tried several iterations, but I am struggling with the globs.

Here's one instance of the plugin code on my webpack.config.js:

     new InjectManifest({
        swSrc: './client/sw-src.js',
        swDest: '../sw.js',
        exclude: [/\.twig$/],
        globPatterns: ['/img/*.{svg,jpg,webp}']
    }),

The directory structure is as follows:

/public
    /dist => there's where the 'regular' webpack assets are
    /img => directory I want to add to precache on top of /dist
    ...

I have also tried to use globDirectory, with no luck.

It works if I manually add the code below to my sw-src.js file, but that is not ideal and prone to errors.

 workbox.precaching.precache([
'/img/circles.svg',
'/img/concept-1.jpg',
......
]);

workbox.precaching.addRoute();

Solution

  • One thing worth mentioning is that Workbox works with webpack assets that have been added to the compilation output. It's possible that you have files in the build context, like images in your repository, but they need to actually be required or otherwise added to the output.

    One easy way to achieve this is to use copy-webpack-plugin. This is really useful when migrating to webpack from other build tools or when your dynamically constructing asset URLs and aren't using webpack loaders.

    EDIT: Adding setup with actual solution:

    This is the new directory setup:

     /assets/img/  => origin directory for copy-webpack-plugin
     /public
       /dist => there's where the 'regular' webpack assets are
       /img => destination directory for copy-webpack-plugin
    

    And the actual code for copy-webpack-plugin and also adjusting the clean-webpack-plugin

        new CleanWebpackPlugin(['public/dist/*.*', 'public/img/*.*']),
        new CopyWebpackPlugin([
            { from: './assets/img/', to: '../img' },
          ]),