Is there a way to import or load libraries in service worker?

Viewed 1151

I am writing a service worker for my app which, in 'activate' state reads and writes to IndexedDB. For reading or writing in IndexedDB, I use a library called 'idb'(https://unpkg.com/idb?module). Is there ant possible way to import libraries in service workers. Also, the library use ES6 imports and exports, will that be a problem?

1 Answers

To import scripts/libraries in service workers I had to use importScripts() rather than fetch() and that did the trick. Also, the imported library gets added to the ServiceWorkerGlobalScope, meaning I had to use this.<library-name> to access the library. Also, the ServiceWorkerGlobalScope doesn't have support for ES6 import/export, that's why I needed to build the package with npm build and then use it.

importScripts('index-min.js');
this.idb();
Related