Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Build an Env Var file for your service workers
/*
By default, service workers cannot access our Vue environment variables.
To allow this, this script collects the variables we want at build time
and places them in a JS file that the service worker can access.
To prevent the leak of sensitive credentials (the SW file is public),
only whitelisted environment variables are built into this file.
Deploy this file alongside your service worker, and import th efile in your service worker (`importScripts('swenv.js');` in Workbox)
This approach is from here: https://stackoverflow.com/questions/54356415/how-can-i-customize-my-service-worker-based-on-environment-variables
*/
require('dotenv').config();
const fs = require('fs');
const OUTPUT_FILE_PATH = './dist/swenv.js';
// Configure vars to expose to the ervice worker here:
const WHITELISTED_ENV_VARS = [
"VUE_APP_REMOTE_PREBUILT_INDEX_FILE_URL"
];
// Runtime
let vars = {}
WHITELISTED_ENV_VARS.forEach(VAR_NAME => {
vars[VAR_NAME] = `${process.env[VAR_NAME]}`
})
fs.writeFileSync(OUTPUT_FILE_PATH,
`
const process = {
env: ${JSON.stringify(vars)}
}
`
);
console.log(`Built env var file to '${OUTPUT_FILE_PATH}'`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment