10

I'm working with workbox-sw and workbox-webpack-plugin My src sw.js file at root folder (same level with my .env file)

How can I get env variables and accessing it into my src sw.js file

This is from my webpack.config.js

new workboxPlugin({
    globDirectory: 'dist',
    globPatterns: ['**/*.{html,js,css,svg,otf,png,jpg,gif}'],
    swSrc: './sw.js',
    swDest: path.join('public', 'sw.js')
})

Every help will be appreciated! Thanks everyone!

Madbarron
  • 335
  • 1
  • 2
  • 9
M.Tae
  • 1,437
  • 1
  • 14
  • 24
  • 1
    I proposed a solution over here (https://stackoverflow.com/a/57051150/1410035) that's for vue-cli, but it relies on a Webpack plugin which you can easily use without vue-cli. This might work for you too, just tweak the plugin to read the env vars you care about (it has access to everything). – Tom Saleeba Jul 16 '19 at 06:24

1 Answers1

0

Because you're using swSrc: './sw.js', that implies that the ./sw.js file will be the basis for the final service worker file that's output. (It will have the precache information inserted into it as part of the build process.)

This means that you can process ./sw.js however you'd like before the workbox-webpack-plugin runs, including modifying it by replacing placeholders with environment variables. I believe that webpack.DefinePlugin is normally used for that?

Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167
  • it didn't work, my workaround: 1. define a variable in webpack config in HtmlWebpackPlugin: `myVariable: process.env.MY_VAR` 2. insert into index.html: ` – kryz81 Nov 21 '18 at 11:23
  • 2
    I couldn't make this work either. Define plugins correctly replaces variables in main js bundle, but not in generated SW. – OndrejRohon Feb 27 '19 at 14:59
  • did you find any solution I am using nuxt js and I want to use the .env file in my custom service workers so if you have found any solution please reply – Bhumit 070 May 14 '21 at 08:44