如何根据环境变量自定义我的Service Worker?

Mad*_*ron 8 environment-variables webpack service-worker workbox-webpack-plugin vue-cli-3

编辑:这看起来像此未解决问题的重复。我是否将此标记为已回答或删除?

我正在Vue CLI 3应用程序内的workbox-webpack-plugin中使用InjectManifest。我要注入的自定义服务人员已经处理了Firebase Cloud Messaging(FCM)。我需要根据我的环境(本地,暂存和生产)来侦听来自不同发件人的消息。

理想情况下,service-worker.js将如下所示:

importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');

firebase.initializeApp({
    'messagingSenderId': process.env.VUE_APP_FCM_SENDER_ID
});
Run Code Online (Sandbox Code Playgroud)

但是,webpack似乎未触及此代码,因为输出服务工作者仍在读取process.env.VUE_APP_FCM_SENDER_ID而不是硬编码的密钥。

如何通过webpack运行服务工作者,以解决环境变量?

shr*_*iek 17

现在对你来说可能为时已晚,但对其他人来说,这就是我继续解决这个问题的方式。此过程仍将.env文件用于与环境相关的变量。
这个想法是创建一个加载.env文件的新脚本,该脚本创建一个新文件,其中填充了来自.env文件的变量。
在构建过程之后,我们只需导入新生成的文件sw.js即可使用。

以下是步骤。
首先创建一个名为的文件swEnvbuild.js,该文件将成为您之后运行的脚本webpack

//swEnvBuild.js - script that is separate from webpack
require('dotenv').config(); // make sure you have '.env' file in pwd
const fs = require('fs');

fs.writeFileSync('./dist/public/swenv.js',
`
const process = {
  env: {
    VUE_APP_FCM_SENDER_ID: conf.VUE_APP_FCM_SENDER_ID
  }
}
`);
Run Code Online (Sandbox Code Playgroud)

其次,我们导入从生成的文件swEnvBuild.js名为swenv.js我们sw.js

// sw.js
importScripts('swenv.js'); // this file should have all the vars declared
console.log(process.env.VUE_APP_FCM_SENDER_ID);
Run Code Online (Sandbox Code Playgroud)

最后,为了使用一个命令,只需在您的 npm 脚本中添加以下内容(假设您运行的是 Linux/Mac)。

scripts: {
  "start": "webpack && node swEnvBuild.js"
}
Run Code Online (Sandbox Code Playgroud)

希望这应该可以解决问题。我希望有更清洁的方法来做到这一点,所以我也很乐意知道其他人的解决方案。


Tom*_*eba 17

我遇到了同样的问题,关键是让 webpack 构建过程输出它使用的环境变量,以便它们可以导入到服务工作者中。这使您不必将您的 env var 定义复制到其他对您的服务工作者进行预处理的内容中(无论如何这很混乱,因为该文件在源代码管理中)。

  1. 创建一个新的 Webpack 插件

    // <project-root>/vue-config/DumpVueEnvVarsWebpackPlugin.js
    const path = require('path')
    const fs = require('fs')
    
    const pluginName = 'DumpVueEnvVarsWebpackPlugin'
    
    /**
     * We to configure the service-worker to cache calls to both the API and the
     * static content server but these are configurable URLs. We already use the env var
     * system that vue-cli offers so implementing something outside the build
     * process that parses the service-worker file would be messy. This lets us
     * dump the env vars as configured for the rest of the app and import them into
     * the service-worker script to use them.
     *
     * We need to do this as the service-worker script is NOT processed by webpack
     * so we can't put any placeholders in it directly.
     */
    
    module.exports = class DumpVueEnvVarsWebpackPlugin {
      constructor(opts) {
        this.filename = opts.filename || 'env-vars-dump.js'
      }
    
      apply(compiler) {
        const fileContent = Object.keys(process.env)
          .filter(k => k.startsWith('VUE_APP_'))
          .reduce((accum, currKey) => {
            const val = process.env[currKey]
            accum += `const ${currKey} = '${val}'\n`
            return accum
          }, '')
        const outputDir = compiler.options.output.path
        if (!fs.existsSync(outputDir)) {
          // TODO ideally we'd let Webpack create it for us, but not sure how to
          // make this run later in the lifecycle
          fs.mkdirSync(outputDir)
        }
        const fullOutputPath = path.join(outputDir, this.filename)
        console.debug(
          `[DumpVueEnvVarsWebpackPlugin] dumping env vars to file=${fullOutputPath}`,
        )
        fs.writeFileSync(fullOutputPath, fileContent)
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在你的 vue-cli 配置中使用插件(vue.config.js或者vue-config/config.default.js如果你的配置被分成几个文件)

    // import our plugin (change the path to where you saved the plugin script)
    const DumpVueEnvVarsWebpackPlugin = require('./DumpVueEnvVarsWebpackPlugin.js')
    
    module.exports = {
      // other stuff...
      configureWebpack: {
        plugins: [
          // We add our plugin here
          new DumpVueEnvVarsWebpackPlugin({ filename: 'my-env-vars.js' })
        ],
      },
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在我们的 Service Worker 脚本中,我们现在可以导入我们用 Webpack 插件编写的文件(它会在构建发生后存在并且 Service Worker 不在开发模式下运行,所以我们应该是安全的)

    importScripts('./my-env-vars.js') // written by DumpVueEnvVarsWebpackPlugin
    const fcmSenderId = VUE_APP_FCM_SENDER_ID // comes from script imported above
    console.debug(`Using sender ID = ${fcmSenderId}`)
    
    // use the variable
    firebase.initializeApp({
        'messagingSenderId': fcmSenderId
    })
    
    Run Code Online (Sandbox Code Playgroud)

它并不完美,但它肯定能完成工作。这是 DRY,因为您只需在一个位置定义所有 env vars,并且整个应用程序使用相同的值。另外,它不处理任何源代码管理中的文件。我不喜欢插件在 Webpack 生命周期中运行得太早,所以我们必须创建dist目录,但希望其他比我更聪明的人能够解决这个问题。

  • 救了我的屁股,谢谢,我用这个片段从 Package.json 中提取我的版本,以便在我的服务工作线程中使用:) 谢谢 (3认同)