All Projects → developit → Workerize Loader

developit / Workerize Loader

🏗️ Automatically move a module into a Web Worker (Webpack loader)

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Workerize Loader

Worker Plugin
👩‍🏭 Adds native Web Worker bundling support to Webpack.
Stars: ✭ 1,840 (-13.82%)
Mutual labels:  webpack, webpack-plugin, web-worker
Svg Sprite Loader
Webpack loader for creating SVG sprites.
Stars: ✭ 1,822 (-14.66%)
Mutual labels:  webpack, webpack-plugin, webpack-loader
Cloudflare Workers Webpack Plugin
Launch Cloudflare Workers to the Edge from the comfort of your build step 🚀
Stars: ✭ 18 (-99.16%)
Mutual labels:  webpack, webpack-plugin, worker
Webpack.js.org
Repository for webpack documentation and more!
Stars: ✭ 2,049 (-4.03%)
Mutual labels:  webpack, webpack-plugin, webpack-loader
Comlink Loader
Webpack loader to offload modules to Worker threads seamlessly using Comlink.
Stars: ✭ 535 (-74.94%)
Mutual labels:  webpack, webpack-loader, worker
Webpack Core Usage
webpack2完整系列课程,欢迎阅读。同时欢迎移步我的react全家桶文章全集: https://github.com/liangklfangl/react-article-bucket
Stars: ✭ 94 (-95.6%)
Mutual labels:  webpack, webpack-plugin, webpack-loader
Webpack Tools
☕️Just a simple webpack sample project.
Stars: ✭ 106 (-95.04%)
Mutual labels:  webpack, webpack-plugin, webpack-loader
React Core Boilerplate
Powerful ASP.NET Core 3 templates with React, true server-side rendering and Docker support
Stars: ✭ 169 (-92.08%)
Mutual labels:  webpack, webpack-plugin
Html Res Webpack Plugin
plugin for generating html in webpack
Stars: ✭ 170 (-92.04%)
Mutual labels:  webpack, webpack-plugin
Multipage Webpack Plugin
A plugin that makes handling templates and asset distribution for multi-page applications using webpack trivial
Stars: ✭ 168 (-92.13%)
Mutual labels:  webpack, webpack-plugin
Virtual Module Webpack Plugin
Adds the contents of a virtual file to webpack's cached file system without writing it to disk
Stars: ✭ 165 (-92.27%)
Mutual labels:  webpack, webpack-plugin
Bundle Stats
In-depth bundle analyzer for webpack(bundle size, assets, modules, packages)
Stars: ✭ 144 (-93.26%)
Mutual labels:  webpack, webpack-plugin
Pug As Jsx Loader
Stars: ✭ 168 (-92.13%)
Mutual labels:  webpack, webpack-loader
Webpack Require From
Webpack plugin that allows to configure path or URL for fetching dynamic imports
Stars: ✭ 142 (-93.35%)
Mutual labels:  webpack, webpack-plugin
Stockroom
🗃 Offload your store management to a worker easily.
Stars: ✭ 1,745 (-18.27%)
Mutual labels:  web-worker, worker
Bs Loader
📻 Bucklescript loader for Webpack and Jest
Stars: ✭ 146 (-93.16%)
Mutual labels:  webpack, webpack-loader
Redux In Worker
Entire Redux in Web Worker
Stars: ✭ 168 (-92.13%)
Mutual labels:  web-worker, worker
Webpack Babel Multi Target Plugin
A Webpack plugin that works with Babel to allow differential loading - production deployment of ES2015 builds targeted to modern browsers, with an ES5 fallback for legacy browsers.
Stars: ✭ 150 (-92.97%)
Mutual labels:  webpack, webpack-plugin
Clean Webpack Plugin
By default, this plugin will remove all files inside webpack's output.path directory, as well as all unused webpack assets after every successful rebuild.
Stars: ✭ 1,888 (-11.57%)
Mutual labels:  webpack, webpack-plugin
React Webpack4 Cook
💯The most powerful webpack4 tutorial in the universe
Stars: ✭ 152 (-92.88%)
Mutual labels:  webpack-plugin, webpack-loader

workerize-loader

workerize-loader npm travis

A webpack loader that moves a module and its dependencies into a Web Worker, automatically reflecting exported functions as asynchronous proxies.

  • Bundles a tiny, purpose-built RPC implementation into your app
  • If exported module methods are already async, signature is unchanged
  • Supports synchronous and asynchronous worker functions
  • Works beautifully with async/await
  • Imported value is instantiable, just a decorated Worker

Install

npm install -D workerize-loader

Usage

worker.js:

// block for `time` ms, then return the number of loops we could run in that time:
export function expensive(time) {
    let start = Date.now(),
        count = 0
    while (Date.now() - start < time) count++
    return count
}

index.js: (our demo)

import worker from 'workerize-loader!./worker'

let instance = worker()  // `new` is optional

instance.expensive(1000).then( count => {
    console.log(`Ran ${count} loops`)
})

Options

Workerize options can either be defined in your Webpack configuration, or using Webpack's syntax for inline loader options.

inline

Type: Boolean Default: false

You can also inline the worker as a BLOB with the inline parameter

// webpack.config.js
{
  loader: 'workerize-loader',
  options: { inline: true }
}

or

import worker from 'workerize-loader?inline!./worker'

name

Type: String Default: [hash]

Customize filename generation for worker bundles. Note that a .worker suffix will be injected automatically ({name}.worker.js).

// webpack.config.js
{
  loader: 'workerize-loader',
  options: { name: '[name].[contenthash:8]' }
}

or

import worker from 'workerize-loader?name=[name].[contenthash:8]!./worker'

publicPath

Type: String Default: based on output.publicPath

Workerize uses the configured value of output.publicPath from Webpack unless specified here. The value of publicPath gets prepended to bundle filenames to get their full URL. It can be a path, or a full URL with host.

// webpack.config.js
{
  loader: 'workerize-loader',
  options: { publicPath: '/static/' }
}

ready

Type: Boolean Default: false

If true, the imported "workerized" module will include a ready property, which is a Promise that resolves once the Worker has been loaded. Note: this is unnecessary in most cases, since worker methods can be called prior to the worker being loaded.

// webpack.config.js
{
  loader: 'workerize-loader',
  options: { ready: true }
}

or

import worker from 'workerize-loader?ready!./worker'

let instance = worker()  // `new` is optional
await instance.ready

import

Type: Boolean Default: false

When enabled, generated output will create your Workers using a Data URL that loads your code via importScripts (eg: new Worker('data:,importScripts("url")')). This workaround enables cross-origin script preloading, but Workers are created on an "opaque origin" and cannot access resources on the origin of their host page without CORS enabled. Only enable it if you understand this and specifically need the workaround.

// webpack.config.js
{
  loader: 'workerize-loader',
  options: { import: true }
}

or

import worker from 'workerize-loader?import!./worker'

About Babel

If you're using Babel in your build, make sure you disabled commonJS transform. Otherwize, workerize-loader won't be able to retrieve the list of exported function from your worker script :

{
    test: /\.js$/,
    loader: "babel-loader",
    options: {
        presets: [
            [
                "env",
                {
                    modules: false,
                },
            ],
        ]
    }
}

Polyfill Required for IE11

Workerize-loader supports browsers that support Web Workers - that's IE10+. However, these browsers require a polyfill in order to use Promises, which Workerize-loader relies on. It is recommended that the polyfill be installed globally, since Webpack itself also needs Promises to load bundles.

The smallest implementation is the one we recommend installing:

npm i promise-polyfill

Then, in the module you are "workerizing", just add it as your first import:

import 'promise-polyfill/src/polyfill';

All worker code can now use Promises.

Testing

Without Webpack

To test a module that is normally imported via workerize-loader when not using Webpack, import the module directly in your test:

-const worker = require('workerize-loader!./worker.js');
+const worker = () => require('./worker.js');

const instance = worker();

With Webpack and Jest

In Jest, it's possible to define a custom transform that emulates workerize-loader on the main thread.

First, install babel-jest and identity-object-proxy:

npm i -D babel-jest identity-object-proxy

Then, add these properties to the "transform" and "moduleNameMapper" sections of your Jest config (generally located in your package.json):

{
  "jest": {
    "moduleNameMapper": {
      "workerize-loader(\\?.*)?!(.*)": "identity-obj-proxy"
    },
    "transform": {
      "workerize-loader(\\?.*)?!(.*)": "<rootDir>/workerize-jest.js",
      "^.+\\.[jt]sx?$": "babel-jest",
      "^.+\\.[jt]s?$": "babel-jest"
    }
  }
}

Finally, create the custom Jest transformer referenced above as a file workerize-jest.js in your project's root directory (where the package.json is):

module.exports = {
  process(src, filename) {
    return `
      async function asyncify() { return this.apply(null, arguments); }
      module.exports = function() {
        const w = require(${JSON.stringify(filename.replace(/^.+!/, ''))});
        const m = {};
        for (let i in w) m[i] = asyncify.bind(w[i]);
        return m;
      };
    `;
  }
};

Now your tests and any modules they import can use workerize-loader! prefixes, and the imports will be turned into async functions just like they are in Workerize.

Credit

The inner workings here are heavily inspired by worker-loader. It's worth a read!

License

MIT License © Jason Miller

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].