question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Bundling workbox via webpack

See original GitHub issue

Library Affected: workbox-build

Browser & Platform: Google Chrome v77 on Windows 10.

I’m using create-react-app 3.2.0 (which bundles webpack 4.41.0).

Up to this point I’ve been pull workbox from the Google CDN using importScripts(). However, this is no use when my PWA is offline. I’d like to bundle workbox using webpack. I’ve worked through your docs but can’t see where I’m supposed to import workbox modules (import isn’t supported in a service worker?).

https://developers.google.com/web/tools/workbox/guides/using-bundlers

image

However, these import statements run in Service Worker scope?

image

I’m using workbox-build and placing the import ... from statements in my template.js.

image

My build.js:

const workbox = require("workbox-build");
  workbox.injectManifest({
    swSrc: "src/ServiceWorker/template.js",
    swDest: "build/sw.js",
    globDirectory: "build",
    globPatterns: [
      "**\/*.{css,html,ico,png,svg,xml}",
      "static\/**\/*.chunk.{js,css}",
      "static\/js\/*.js"
    ]
  }).then(({ count, size, warnings }) => {
    warnings.forEach(console.warn);
    console.log(
      `${count} files will be precached (${Math.floor(size / 1024)} KB)`
    );
  });

Where am I supposed to import functions from workbox-* packages?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:9 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
dsebastiencommented, Jan 30, 2020

Ok, thanks a ton @jeffposnick. I was making my life harder than needs be.

Here’s what I did to fix this:

  • Angular: build as usual
  • service worker TS to JS using Webpack + TS loader (basic config)
  • workbuild-build with a simple config/globs to inject the list of assets

Time to enjoy some more TypeScript goodness 😉

0reactions
Yashs911commented, Jun 18, 2021

@jeffposnick Sorry for asking here but can you please guide me on what should I do: I am currently using workbox CDN for my sw.js But now I want to move away from CDN, the project also uses webpack but when I try to use the workbox-webpack plugin it works but the generated file static/build/sw.js contain 10248 lines of code so is it normal? or I am missing something. And How can I only precache few selected files and not precache any files generated by webpack? webpack.config.js

/* eslint-env node, es6 */
// https://webpack.js.org/configuration
const
    webpack = require('webpack'),
    path = require('path'),
    {InjectManifest} = require('workbox-webpack-plugin'),
    prod = process.env.NODE_ENV === 'production',
    // The output directory for all build artifacts. Only absolute paths are accepted by
    // output.path.
    distDir = path.resolve(__dirname, 'static/build');

module.exports = {
    // Apply the rule of silence: https://wikipedia.org/wiki/Unix_philosophy.
    stats: {
        all: false,
        // Output a timestamp when a build completes. Useful when watching files.
        builtAt: true,
        errors: true,
        warnings: true
    },

    // Fail on the first build error instead of tolerating it for prod builds. This seems to
    // correspond to optimization.noEmitOnErrors.
    bail: prod,

    // Specify that all paths are relative the Webpack configuration directory not the current
    // working directory.
    context: __dirname,

    // A map of ResourceLoader module / entry chunk names to JavaScript files to pack.
    entry: {
        all: './openlibrary/plugins/openlibrary/js/index.js',
        vue: './openlibrary/plugins/openlibrary/js/vue.js',
    },

    resolve: {
        alias: {}
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery'
        }),
       new InjectManifest({
            swSrc: path.resolve(__dirname, 'static', 'src-sw.js'),
            swDest: 'sw.js',
        })
    ],
    module: {
        rules: [{
            test: /\.js$/,
            use: {
                loader: 'babel-loader',
                options: {
                    // Beware of https://github.com/babel/babel-loader/issues/690.
                    // Changes to browsers require manual invalidation.
                    cacheDirectory: true
                }
            }
        }, {
            test: /\.less$/,
            use: [
                {
                    loader: 'style-loader'
                },
                {
                    loader: 'css-loader',
                    options: {
                        url: false
                    }
                },
                {
                    // compiles Less to CSS
                    loader: 'less-loader'
                }
            ]
        }]
    },
    optimization: {
        splitChunks: {
            cacheGroups: {
                // Turn off webpack's default 'vendors' cache group. If this is desired
                // later on, we can explicitly turn this on for clarity.
                // https://webpack.js.org/plugins/split-chunks-plugin/#optimization-splitchunks
                vendors: false,

            }
        },
        // Don't produce production output when a build error occurs.
        noEmitOnErrors: prod
    },

    output: {
        // Specify the destination of all build products.
        path: distDir,
        // base path for build products when referenced from production
        // (see https://webpack.js.org/guides/public-path/)
        publicPath: '/static/build/',

        // Store outputs per module in files named after the modules. For the JavaScript entry
        // itself, append .js to each ResourceLoader module entry name.
        filename: '[name].js',

        // This option determines the name of **non-entry** chunk files.
        chunkFilename: '[name].[contenthash].js',

        // Expose the module.exports of each module entry chunk through the global
        // ol (open library)
        library: ['ol'],
        libraryTarget: 'this'
    },

    // Accurate source maps at the expense of build time.
    // The source map is intentionally exposed
    // to users via sourceMapFilename for prod debugging.
    devtool: 'source-map',
    mode: prod,

    performance: {
        maxAssetSize: 703 * 1024,
        maxEntrypointSize: 703 * 1024,
        // Size violations for prod builds fail; development builds are unchecked.
        hints: prod ? 'error' : false
    }
};
Read more comments on GitHub >

github_iconTop Results From Across the Web

Build A PWA With Webpack And Workbox - Smashing Magazine
This tutorial will help you transform an app that doesn't work offline into a PWA that works offline and shows an update available...
Read more >
workbox-webpack-plugin - Chrome Developers
Generate a service worker or inject a precache manifest, using the webpack build tool.
Read more >
Create a service worker with Workbox, Webpack and TypeScript
Create a service worker with Workbox, Webpack and TypeScript ... that contains a list of the entry points/generated files of the Webpack bundling...
Read more >
Progressive Web Application - webpack
We'll achieve this using a Google project called Workbox which provides ... Asset Size Chunks Chunk Names app.bundle.js 545 kB 0, 1 [emitted]...
Read more >
How to use the workbox-webpack-plugin.GenerateSW ... - Snyk
return { files: manifestFiles, }; }, }), // Moment.js is an extremely popular library that bundles large locale files // by default due...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found