'How to import a library like moment.js into a web worker

Can I import a library installed with npm into a web worker?

I need to use the moment.js library into a web worker.

It is installed via npm into the node_modules/moment directory

I already have tried with this at the top of the worker.js file:

importScripts('/node_modules/moment/moment.js');

But I get

GET http://192.168.2.1:8100/node_modules/moment/moment.js 404 (Not Found)


Solution 1:[1]

Yes, it's possible, chances are you're already using a popular bundler like webpack or parcel, but even if you're not it's still possible, though probably not directly from node_modules

With Parcel

main.js
// relative path to the worker from current file
const worker = new Worker('../utils/myWorker.js');
myWorker.js
// use import like you would in any other file
import moment from 'moment';

console.log(`From worker: worker started at ${moment().format('HH:mm:ss')}`);

With Webpack (as entry)

main.js
// relative to the expected public path (have in mind any filename transforms like hashing)
const worker = new Worker('myWorker.bundle.js');
myWorker.js
// use import like you would in any other file
import moment from 'moment';

console.log(`From worker: worker started at ${moment().format('HH:mm:ss')}`);

webpack.config.js

{
  entry: {
    main: './src/app/main.js'
    worker: './src/utils/myWorker.js',
  },
  output: {
    path: `${ROOT_PATH}/public`,
    filename: '[name].bundle.js',
  }
}

With Webpack (worker-loader)

Install the loader

main.js
// relative path to the worker from current file
import Worker from '../utils/myWorker.worker.js';

const worker = new Worker();
myWorker.worker.js
// use import like you would in any other file
import moment from 'moment';

console.log(`From worker: worker started at ${moment().format('HH:mm:ss')}`);

webpack.config.js

{
  module: {
    rules: [
      {
        test: /\.worker\.js$/,
        use: { loader: 'worker-loader' }
      }
    ]
  }
}

With CRA (Create React App) (worker-loader) inline loader

Using an inline loader

main.js
/* eslint-disable import/no-webpack-loader-syntax */
import Worker from "worker-loader!./myWorker.worker.js";

const worker = new Worker();
myWorker.worker.js
// use import like you would in any other file
import moment from 'moment';

console.log(`From worker: worker started at ${moment().format('HH:mm:ss')}`);

You can always import the library from a CDN

myWorker.js
importScripts('//cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js');

console.log(`From worker: worker started at ${moment().format('HH:mm:ss')}`);

Other bundlers

  • Web workers cannot importScripts from parent folders for security reasons
  • The node_modules folder is usually at the root of the project so you can't access it with importScripts
  • The bundler needs to be configured so that the content can be aliased or copied to a location the worker can access

AngularCLI, Ionic, CRA

For projects using webpack as a bundler the 2 webpack solutions can be adapted as long as you can access the webpack config and customize it. If you can't access the config (CRA) you can use the inline loader from the "With CRA" example

The "Webpack (as entry)" example was actually borrowed from Angular CLI generated app with Web Workers

  • It explains how to modify the setup to bootstrap angular using web workers
  • It have been referenced as a webworker solution for Ionic projects too

Note on TypeScript

{
  "extends": "../generic-tsconfig.json",
  "compilerOptions": {
    "lib": ["esnext", "webworker"],
  }
}

Solution 2:[2]

As of 12 August 2020. I have been successful using npm modules with CloudFlare Workers by doing these steps.

Create new project:

wrangler generate your-project
cd your-project

Set 'wrangler.toml' to use webpack:

name = "your-project"
type = "webpack"
account_id = "your-account-id"
workers_dev = true
route = ""
zone_id = ""

Import your npm modules into the index.js file: eg.

const qr = require('qr-image')

In terminal / cmd:

wrangler publish

It automatically creates the worker packaged using webpack. Now it should just work.

Hope this helps someone, was looking on google for ages and then just decided to try the tutorials and found this out!

Solution 3:[3]

For webpack 5 onwards you can use web workers and import libraries without using worker-loader or any bundler in simple way as mentioned here

I managed to run my web worker and import libraries in same way.

In the file you want to import web worker

// here ./deep-thought.js is the path to the web worker

const worker = new Worker(new URL('./deep-thought.js', import.meta.url));

worker.postMessage({
  question:
    'The Answer to the Ultimate Question of Life, The Universe, and Everything.',
});
worker.onmessage = ({ data: { answer } }) => {
  console.log(answer);
};

In the web worker file,

// just to show it supports importing files into web worker in generic way

import JSONstream from 'JSONStream';

 self.onmessage = function (e) {
   // worker code inside

   // just to show it supports importing and using files into web worker in generic way

   const jsonParser = JSONstream.parse();
 }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 cuznerdexter
Solution 3 Abdullah Jamal