问题:我无法让服务人员访问我的.env变量
我发现的唯一解决方案是将变量存储到生成的js文件中,为此我正在使用 Vue PWA 。
Vue 配置
module.exports = {
pwa: {
name: 'Fintask App',
themeColor: '#3aa9ff',
msTileColor: '#3aa9ff',
appleMobileWebAppCapable: 'yes',
appleMobileWebAppStatusBarStyle: 'black',
// configure the workbox plugin
workboxPluginMode: 'InjectManifest',
workboxOptions: {
// swSrc is required in InjectManifest mode.
swSrc: 'src/service-worker.js',
// ...other Workbox options...
}
}
};
我的服务工作者配置
importScripts('swenv.js'); // this generates an error: Uncaught ReferenceError: Cannot access 'process' before initialization
workbox.setConfig({
debug: false,
});
workbox.precaching.precacheAndRoute([]);
workbox.routing.registerRoute(
new RegExp(`${process.env.VUE_APP_API_ROOT_URL}/organization/(.*)`),
workbox.strategies.networkFirst({
cacheName: 'organization',
}),
);
应该生成我的swenv.js的我的swEnvBuild
//swEnvBuild.js - script that is separate from webpack
require('dotenv').config();
const fs = require('fs');
fs.writeFileSync("public/swenv.js",
`const process = {
env: {
VUE_APP_API_ROOT_URL: process.env.VUE_APP_API_ROOT_URL
}
}`);
我的swenv.js
const process = {
env: {
VUE_APP_API_ROOT_URL: process.env.VUE_APP_API_ROOT_URL
}
}
这仍然对我不起作用,我确实找到了基于此方法的不同解决方案,我只是希望有更好的方法
我的输出
swenv.js:3 Uncaught ReferenceError: Cannot access 'process' before initialization
at swenv.js:3
at service-worker.js:3
Error during service worker registration: TypeError: Failed to register a ServiceWorker for scope ('http://localhost/') with script ('http://localhost/service-worker.js'): ServiceWorker script evaluation failed
不知道为什么会收到此错误,此结果是在我的apache服务器中生成的