Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

parcel-plugin-precaching-sw

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

parcel-plugin-precaching-sw - npm Package Compare versions

Comparing version 0.0.1 to 0.0.2

example/build.js

8

example/app.js

@@ -1,3 +0,5 @@

const h1 = document.createElement('h1');
h1.innerHTML = 'I am the app!';
document.body.appendChild(h1);
window.onload = function() {
const h1 = document.createElement('h1');
h1.innerHTML = 'I am the app!';
document.body.appendChild(h1);
};
{
"name": "test-serviceworker",
"name": "example-parcel-plugin-precaching-serviceworker",
"description": "Simple example that shows how to use and configure the precaching serviceworker plugin",

@@ -7,3 +7,3 @@ "license": "MIT",

"type": "git",
"url": "https://tgrep.nl/dvandermeer/tgsw"
"url": "https://github.com/tweedegolf/parcel-plugin-precaching-sw.git"
},

@@ -17,2 +17,3 @@ "scripts": {

"parcel": "^1.10.3",
"parcel-bundler": "^1.10.3",
"parcel-plugin-precaching-sw": "file:.."

@@ -32,4 +33,14 @@ },

"fileName": "sw.js",
"outDir": "./"
"outDir": "./",
"index.html": {
"bypass": true
},
"app.js": {
"fileName": "javascript-sw.js",
"allowed": [
"js",
"map"
]
}
}
}

@@ -0,4 +1,56 @@

/* eslint-disable no-console */
const { readFileSync, writeFileSync, unlinkSync, existsSync } = require('fs');
const path = require('path');
const defaultConfig = {
'bypass': false,
'allowed': [
'css',
'js',
'woff2',
'svg',
'ico',
'png',
'webmanifest'
],
'additional': [],
'offlineUrl': '/offline.html',
'fileName': 'sw.js',
'outDir': path.resolve(__dirname, '../'),
};
const getConfig = (pkg, bundleId) => {
const conf = pkg['precachingSW'] || {};
let {
bypass = defaultConfig.bypass,
allowed = defaultConfig.allowed,
additional = defaultConfig.additional,
outDir = defaultConfig.outDir,
fileName = defaultConfig.fileName,
offlineUrl = defaultConfig.offlineUrl,
} = conf;
const bundleConfig = conf[bundleId];
if (bundleConfig) {
({
bypass = bypass,
allowed = allowed,
additional = additional,
outDir = outDir,
fileName = fileName,
offlineUrl = offlineUrl,
} = bundleConfig);
}
return {
bypass,
allowed,
additional,
offlineUrl,
path: path.resolve(outDir, fileName),
};
};
/**

@@ -25,26 +77,24 @@ * Flatten the bundle structure to array of strings

bundler.on('bundled', async (bundle) => {
const pkg = await bundle.entryAsset.getPackage();
const swConfig = pkg['precachingSW'];
const swOutDir = swConfig.outDir || path.resolve(__dirname, '../');
const fileName = swConfig.fileName || 'sw.js';
const offlineUrl = swConfig.offlineUrl || './offline.html';
const swPath = path.resolve(swOutDir, fileName);
// console.log('BUNDLE', bundle);
let pkg;
try {
pkg = await bundle.entryAsset.getPackage();
} catch (e) {
console.error('ERROR', e);
return;
}
// console.log('PKG', pkg);
const bundleId = bundle.entryAsset.id;
// console.log('ID', bundleId);
const config = getConfig(pkg, bundleId);
// console.log('CONFIG', config);
if (swConfig.bypass === true) {
if (existsSync(swPath)) {
unlinkSync(swPath);
if (config.bypass === true) {
if (existsSync(config.path)) {
unlinkSync(config.path);
}
console.log(`Not generating a precaching serviceworker for "${bundleId}".`);
return;
}
const allowed = swConfig.allowed || [
'css',
'js',
'woff2',
'svg',
'ico',
'png',
'webmanifest'
];
const assets = getAssets(bundle).filter((name) => {

@@ -55,7 +105,9 @@ if (name.includes('/icon_')) {

const ext = name.split('.').pop();
return allowed.includes(ext);
return config.allowed.includes(ext);
}).map(name => name.replace(outDir, '/assets'));
assets.push(...swConfig.additional);
assets.push(offlineUrl);
if (config.additional && config.additional.length > 0) {
assets.push(...config.additional);
}
assets.push(config.offlineUrl);
const cache = JSON.stringify(assets);

@@ -70,9 +122,10 @@ const cacheName = `${pkg.name}-${bundle.entryAsset.hash.substr(0, 8)}`;

const sw = template
.replace('%{created}', new Date())
.replace('\'%{caches}\'', cache)
.replace('%{cacheName}', cacheName)
.replace('%{offlineUrl}', offlineUrl)
.replace('%{offlineUrl}', config.offlineUrl)
.replace(/"/g, '\'');
writeFileSync(swPath, sw);
writeFileSync(config.path, sw);
});
};
{
"name": "parcel-plugin-precaching-sw",
"description": "Parcel plugin that creates a precaching service worker",
"version": "0.0.1",
"version": "0.0.2",
"main": "./index.js",

@@ -6,0 +6,0 @@ "repository": {

@@ -0,1 +1,2 @@

const created = '%{created}';
const caches = '%{caches}';

@@ -2,0 +3,0 @@ const cacheName = '%{cacheName}';

@@ -22,3 +22,3 @@ # Parcel plugin that creates a precaching serviceworker

- `bypass` → When set to `true` no serviceworker is created. Defaults to `false`.
- `allowed` → Array of file extensions that will be added to the cache. Defaults an array containing the following extensions:
- `allowed` → Array of file extensions that will be added to the cache. Defaults to an array containing the following extensions:
- css

@@ -32,3 +32,3 @@ - js

- `additional` → Array containing additional files that must be added to the cache.
- `offlineUrl` → Url of the offline html file, this file will be added to the cache as well.
- `offlineUrl` → Url of the offline html file, this file will be added to the cache as well. Defaults to `offline.html`.
- `fileName` → The name of the file that holds the generated serviceworker. Defaults to `sw.js`.

@@ -42,8 +42,72 @@ - `outDir` → The path to the directory where the serviceworker file will be saved to. Defaults to `./`.

In the package.json file you see that the plugin is added to the `devDependencies`. I am using `file:..` here so the local version of the plugin will be installed; this is handy if you want to tinker a bit with the plugin code. In your real-life project it will look something like `^0.0.1`.
In the package.json file you see that the plugin is added to the `devDependencies`. We are using `file:..` here so the local version of the plugin will be installed; this is handy if you want to tinker a bit with the plugin code. In your real-life project it will look something like `^0.0.2`.
Also in the package.json file you see the `precachingSW` entry; just play around with the parameters to get a grip on how they work.
The example project itself, and thus the project for which the plugin generates a precaching serverworker is fairly simple: it contains an index.html that embeds a stylesheet (app.css) and a javascript file (app.js). In the stylesheet a background image is applied to the body; because the jpeg extension is in the `allowed` array, you can see in the generated serviceworker file that the background image gets cached as well.
The example project itself, and thus the project for which the plugin generates a precaching serviceworker is fairly simple: it contains an index.html that embeds a stylesheet (app.css) and a javascript file (app.js). In the stylesheet a background image is applied to the body; because the jpeg extension is in the `allowed` array, you can see in the generated serviceworker file that the background image gets cached as well.
## Building the example using a Node script
In some cases you need to create multiple bundles and these bundles may require different settings. Take a look at the `build.js` script inside the example folder. This script creates 2 bundlers by script:
```javascript
const bundlerJs = new Parcel('app.js', config);
const bundlerHtml = new Parcel('index.html', config);
```
The config object you see above is the Parcel bundler configuration object and additional entries get stripped off when the bundler bundles the files. So we need find another way to pass per-bundle configurations to the precaching plugin.
For this we use the `bundle.entryAsset.id`, this is the name of the file you pass as first argument to the Parcel constructor. So in our case we have the ids `app.js` and `index.html`.
By using this id as an extra entry to the `precachingSW` object every bundle can have its own configuration
```javascript
"precachingSW": {
// generic settings
"bypass": false,
"allowed": [
"js",
"css",
"map",
"jpeg",
"html"
],
"additional": [],
"offlineUrl": "/offline.html",
"fileName": "sw.js",
"outDir": "./",
// bundle specific settings
"index.html": {
"bypass": true
},
"app.js": {
"fileName": "javascript-sw.js",
"allowed": [
"js",
"map"
]
}
}
```
Please note that bundle specific settings will be merged with the generic settings. For instance the second bundle specific entry `app.js` uses the values set in the generic settings for `outDir`, `offlineUrl` and so on, but overrules both `fileName` and `allowed`. Thus the resulting settings of the `app.js` serviceworker will become:
```json
"bypass": false,
"allowed": [
"js",
"map"
],
"additional": [],
"offlineUrl": "/offline.html",
"fileName": "javascript-sw.js",
"outDir": "./",
```
***
Background image from: https://www.pexels.com/

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc