如何在自定义Service Worker中加载自定义库函数?
问题描述
我制作了一个自定义库(文件路径为src/mylib.js):
export function myfunc(){ // do stuff here }
我使用Rollup将其打包为UMD模块,配置如下:
import resolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; import { babel } from '@rollup/plugin-babel'; export default [ { input: 'src/mylib.js', output: [ { file: 'dist/mylib.js', format: 'umd', name: 'firebaseLibServiceWorker', sourcemap: true } ], plugins: [ resolve(), commonjs(), babel({ exclude: 'node_modules/**', babelHelpers: 'bundled', presets: [ ['@babel/preset-env', { targets: { browsers: ['> 0.25%', 'not dead', 'ie 11'] } }] ] }), ], }, ];
并将其作为模块发布到npm,package.json配置如下:
{ "name": "mylib", "version": "1.0.0", "description": "blahblahblag", "type": "module", "scripts": { "build": "rollup -c", "start": "rollup -c --watch", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "TechInsSoftware", "license": "MIT", "dependencies": { }, "devDependencies": { "@babel/core": "^7.24.5", "@babel/preset-env": "^7.24.5", "@rollup/plugin-babel": "^6.0.4", "@rollup/plugin-commonjs": "^25.0.7", "@rollup/plugin-node-resolve": "^15.2.3", "rollup": "^4.17.2" } }
我希望在自定义Service Worker中通过importScripts引入该库并调用函数:
importscripts('https://mydnb.example.com/dist/mylib.js'); myfunc()
但执行时出现错误:
Uncaught ReferenceError: myfunc is not defined
解决方案
问题出在两个地方:UMD模块的全局访问方式,以及importScripts的拼写错误。
1. 修正API拼写错误
首先,importscripts是拼写错误,正确的API名称是importScripts(首字母S大写),这个错误会导致库加载失败,直接引发函数未定义的报错。
2. 正确访问UMD模块的函数
你在Rollup配置里给UMD模块指定了全局变量名称firebaseLibServiceWorker,打包后的函数会挂载到这个全局对象上,而不是直接暴露为全局函数。你可以选择以下两种方式解决:
方式一:通过全局对象调用函数
修改Service Worker代码,通过指定的全局对象访问myfunc:
importScripts('https://mydnb.example.com/dist/mylib.js'); firebaseLibServiceWorker.myfunc();
方式二:修改Rollup配置,直接挂载到全局上下文
如果你希望直接调用myfunc,可以调整Rollup的输出配置,将全局变量设为Service Worker的全局上下文self,并开启extend: true:
output: [ { file: 'dist/mylib.js', format: 'umd', name: 'self', sourcemap: true, extend: true } ]
重新打包后,myfunc会直接挂载到Service Worker的全局self对象上,此时你就可以直接调用myfunc()了。
内容的提问来源于stack exchange,提问作者Dimitrios Desyllas
相关产品推荐
相关产品推荐

