Search code examples
javascriptweb-workerrollup

How I can load my library function in my custom service worker?


I am making a custom library (file src/mylib.js):


export function myfunc(){
  // do stuff here
}

Where I use rollup to build it as umd module:

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']
            }
          }]
        ]
      }),
    ],
  },
];

And I export it as a module into npm:

{
  "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"
  }
}

And what I want to achieve it to use it via importScripts upon my suctom service worker, whenever I want to use it:

importscripts('https://mydnb.example.com/dist/mylib.js');

But I am unable to do so:

importscripts('https://mydnb.example.com/dist/mylib.js');
myfunc()

Cause I get:

Uncaught ReferenceError: myfunc is not defined

How I can fix this?


Solution

  • In order for this to work you need to assign the function into self:

    
    function myfunc(){
      // do suff
    }
    
    // Export for service worker
    if (typeof self !== 'undefined') {
      self.myfunc = myfunc;
    }
    
    
    // Export for browser
    if (typeof self !== 'undefined') {
      self.myfunc = myfunc;
    }
    
    export default myfunc
    
    

    And then the function myfunc will be accessible once you do:

    importscripts('https://mydnb.example.com/dist/mylib.js');