Bundle firebase-messaging-sw.js deps with Webpack

Viewed 1092

Say I have a file in which I initialize Firebase and import its dependencies.

app.js

import firebase from 'firebase'

firebase.initializeApp()

Now I want to reference the same dependencies for firebase-messaging-sw.js as well but since it needs to be in the root, how can I tell Webpack to solve the dependencies?

Sure enough I could go with

importScripts('https://www.gstatic.com/firebasejs/4.1.3/firebase.js')

But that would download me the code twice.

2 Answers

This plugin solved my problem. firebase-messaging-sw.js will be copied to root folder after building production

let config = {
  plugins: [
   ...,
    new CopyPlugin([
      {
        from: 'firebase-messaging-sw.js',
        to: 'firebase-messaging-sw.js'
      }
    ])
  ]
}

If you have more than 1 service worker file with different environments. It can be like this

let config = {
  plugins: [
   ...,
    new CopyPlugin([
      {
        from: isProduction ? 'firebase-messaging-sw-prod.js' : 'firebase-messaging-sw.js',
        to: 'firebase-messaging-sw.js'
      }
    ])
  ]
}

Not 100% clear on what you're trying to do, are you trying to treat a script that you load remotely as a webpack dependency? Webpack's standard module-building assumes that the modules you import are all local files available at build time. To treat a remote script as a dependency, I would recommend defining it as an external dependency in webpack: https://webpack.js.org/configuration/externals/

In this example of an externals config (taken from the linked docs):

externals: {
  jquery: 'jQuery'
}

... you would reference the jquery library with import jquery from "jquery" (using the key you specified in externals config). At runtime, webpack will look for a global var named jQuery (the value for that key in your externals config). Webpack takes no responsibility for actually loading the dependency in this case, it assumes the global you specified will already be defined at runtime -- which is why they're called "external" dependencies -- so you would have to load the dependency (the firebase library) separately before your webpack bundle.

Related