Read env variable from service worker file using workbox
Asked Answered
W

1

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!

Wyattwyche answered 23/1, 2018 at 9:49 Comment(1)
I proposed a solution over here (https://mcmap.net/q/574784/-how-can-i-customize-my-service-worker-based-on-environment-variables) 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).Community
H
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?

Homologous answered 26/1, 2018 at 21:12 Comment(3)
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: <script>var MY_VAR = "<%= htmlWebpackPlugin.options.myVariable %>"; 3. get the variable in your service worker: const myVariable = self.MY_VAR;Reahard
I couldn't make this work either. Define plugins correctly replaces variables in main js bundle, but not in generated SW.Various
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 replyCampbellite

© 2022 - 2024 — McMap. All rights reserved.