Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Vue PWA] Feature - Inject environment variables in service-worker.js #5047

Open
esynaps opened this issue Jan 7, 2020 · 4 comments
Open

Comments

@esynaps
Copy link

esynaps commented Jan 7, 2020

What problem does this feature solve?

We need to inject environment variables in service-worker.js

process.env.VUE_APP_MY_VAR should be replaced by the DefinePlugin of webpack (automatically configured by Vue CLI) by a value defined in my .env but it works for all files except the "service-worker.js"

My vue.config.js

module.exports = {
  transpileDependencies: [],
  configureWebpack: {
    resolve: {
      symlinks: false
    }
  },
  pwa: {
    workboxPluginMode: 'InjectManifest',
    workboxOptions: {
      swSrc: 'public/service-worker.js'
    }
  }
}

What does the proposed API look like?

I found two obscure solutions for this problem :

The first one : https://stackoverflow.com/a/57051150/4864628

The second (better): https://github.com/diachedelic/vue-cli-plugin-bundle-service-worker

This last solution uses webpack to bundle the service-worker.js file. In my opinion this should be the default behavior of Vue PWA.

@esynaps esynaps changed the title [Vue PWA] Inject environment variables in service-worker.js [Vue PWA] Feature - Inject environment variables in service-worker.js Jan 7, 2020
@rodrigogs
Copy link

So... no way?

@esynaps
Copy link
Author

esynaps commented Apr 3, 2020

While waiting for the managers to take care of it, I recommend this link which served as an alternative

https://stackoverflow.com/a/57051150/4864628

@Phoen1x84
Copy link

This would be a great feature. I'm having the same issue and need to change the service worker to cache different API requests depending on deployed environment e.g. QA, UAT and Prod.

@Tobiaqs
Copy link

Tobiaqs commented Mar 27, 2024

You can encapsulate variables into a query string appended to the service worker script path.

navigator.serviceWorker.register(
    import.meta.env.VITE_SW_PATH + (import.meta.env.VITE_SW_PATH.includes('?') ? '&' : '?') + 'vapid_public_key=' + import.meta.env.VITE_VAPID_PUBLIC_KEY
)

In service worker:

variables = Object.fromEntries(self.serviceWorker.scriptURL.split('?')[1].split('&').map((value, idx) => idx === 1 ? decodeURIComponent(value) : value))

Use .env.development during development & .env.production or actual environment variables to influence what happens at build time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants