简体   繁体   English

带有工作箱和Gulp的服务人员,如何添加我自己的规则?

[英]Service worker with workbox and Gulp, how to add my own rules?

I just started to work with workbox and I am using Gulp to generate my service worker with the following code in the example: https://developers.google.com/web/tools/workbox/get-started/gulp 我刚刚开始使用Workbox,并且正在使用Gulp在示例中使用以下代码生成服务工作者: https : //developers.google.com/web/tools/workbox/get-started/gulp

It generates the service-worker file properly, but the thing I do not understand is how can I add my own code to the file? 它可以正确生成service-worker文件,但是我不明白的是如何将自己的代码添加到文件中? Lets say I want to add the following route: 可以说我想添加以下路线:

 workboxSW.router.registerRoute( 'https://pixabay.com/get/(.*)', cacheOneWeekStrategy ); 

Now if I run the gulp task again it overwrites my own route. 现在,如果我再次运行gulp任务,它将覆盖我自己的路线。 How can I add my own code? 如何添加自己的代码? I also want to add some event listeners etc. 我也想添加一些事件监听器等。

Update: so far I have found out that I can use injectManifest() which will inject routes to the file inside workboxSW.precache([]); 更新:到目前为止,我发现我可以使用injectManifest()来将路由注入到workboxSW.precache([])内部的文件中; But I still need to copy the actual service worker script somehow. 但是我仍然需要以某种方式复制实际的服务工作者脚本。

I could not figure out any other way. 我找不到其他办法。 This is my solution. 这是我的解决方案。 I copy workbox from node_modules and then I write my code to sw.js and then I use inject-manifest to inject the routes to my own code. 我从node_modules复制工作箱,然后将代码编写到sw.js,然后使用inject-manifest将路由注入到自己的代码中。

 gulp.task('copy-workbox', () => { return gulp.src(['node_modules/workbox-sw/build/importScripts/workbox-sw.prod*.js']) .pipe(rename('workbox.js')) .pipe(gulp.dest('app')); }); gulp.task('inject-manifest', () => { return wbBuild.injectManifest({ swSrc: './app/sw.js', swDest: './app/service-worker.js', globDirectory: './app/', globPatterns: ['**\\/*.{html,js,css,png}'], globIgnores: ['admin.html'] }) .then(() => { console.log('Service worker generated.'); }); }); 

UPDATE: after some reading I figured out it is not a good idea to rename the workbox. 更新:经过一番阅读,我发现重命名工作箱不是一个好主意。 However I couldn't find a way to do this otherwise. 但是,我找不到其他方法。

This was a bit of a sticky point for earlier versions of Workbox. 对于早期版本的Workbox,这有点棘手。

Workbox v3 provides some more options to make this easier. Workbox v3提供了更多选项来简化此操作。

  1. There is a CDN you can use: https://developers.google.com/web/tools/workbox/guides/get-started 您可以使用CDN: https//developers.google.com/web/tools/workbox/guides/开始使用
  2. To host the files yourself, you can use copyWorkboxLibraries() which will save the files to a specific location and returns the path of the files ( More details here ) 要自己托管文件,可以使用copyWorkboxLibraries()将文件保存到特定位置并返回文件的路径( 此处有更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM