next-workbox-webpack-plugin
Webpack plugin with workbox, it helps you build a Progressive Web App powered by Next.js. Generating service worker scripts and precache manifest of Next.js's pages and chunks.
Install
$ npm install -d next-workbox-webpack-plugin
Usage
const nextWorkboxWebpackPlugin = require('next-workbox-webpack-plugin');
nextWorkboxWebpackPlugin({
buildId,
distDir: '.next',
importWorkboxFrom: 'local',
precacheManifest: true,
removeDir: true,
swDestRoot: './static/',
swURLRoot: '/static'
...WorkboxBuildOptions,
});
Visit workbox-build page for more information.
Usage in next.config.js
const NextWorkboxWebpackPlugin = require('next-workbox-webpack-plugin');
module.exports = {
webpack: (config, {isServer, dev, buildId, config: {distDir}}) => {
if (!isServer && !dev) {
config.plugins.push(new NextWorkboxWebpackPlugin({
distDir,
buildId
}))
}
return config
}
}
How it works
Custom Server
static/workbox
├── next-precache-manifest-d42167a04499e1887dad3156b93e064d.js
├── sw.js
└── workbox-v3.0.0-beta.0
├── workbox-background-sync.dev.js
├── ...
├── workbox-sw.js
Now 2.0
To use this plugin on now 2.0, you should have more work below
- Using fixed build id with
generateBuildId. It will be used at path of sw asserts
- Set fixed path for sw assets. one is
swDestRoot, another is swURLRoot. For service sw.js and manifest on now 2.0, we have to put those of files under .next as a part of app
const NextWorkboxWebpackPlugin = require('next-workbox-webpack-plugin');
module.exports = {
webpack: (config, { isServer, dev, buildId, config: { distDir } }) => {
if (!isServer && !dev) {
config.plugins.push(
new NextWorkboxWebpackPlugin({
importWorkboxFrom: 'cdn',
distDir,
buildId,
// destination root for sw assets, sw.js
swDestRoot: '.next/static/my-build-id/pages',
// root url for sw.js
swURLRoot: '_next/static/my-build-id/pages'
})
);
}
return config;
},
generateBuildId: async () => {
return 'my-build-id'
}
};
- Update your routes for sw.js
{
"version": 2,
"routes": [{ "src": "/sw.js", "dest": "_next/static/my-build-id/pages/sw.js" }],
"builds": [{ "src": "next.config.js", "use": "@now/next" }]
}
Examples
- Hello PWA: You can learn how to use the webpack plugin basically
- HNPWA: Simple HNPWA apps with Next.js
License
MIT © Jimmy Moon