Git Product home page Git Product logo

worker-loader's Introduction

NativeScript Worker Loader and NativeScriptWorkerPlugin

This is a fork of the official Worker Loader for Webpack.

Install

You can install this plugin from npm:

npm i -D nativescript-worker-loader

Usage in JavaScript projects

  1. Write a worker file:
// app/worker.js
require("globals");

global.onmessage = function(msg) {
    console.log("Inside JS worker...");
    global.postMessage("JS worker");
}
  1. Import the worker file with the webpack loader inlined:
// app/main.js
const MyWorker = require("nativescript-worker-loader!./worker.js");

const worker = new MyWorker();
worker.postMessage({a: 1});
worker.onmessage = function(event) {...};
worker.addEventListener("message", function(event) {...});
  1. Configure your webpack.config.js to use the NativeScriptWorkerPlugin.
// webpack.config.js
const { NativeScriptWorkerPlugin } = require("nativescript-worker-loader/NativeScriptWorkerPlugin");
// ...

module.exports = env => {
    // ...

    const config = {
        //...
        plugins: [
            new NativeScriptWorkerPlugin(),
            // ...
        ]
    }
}

Usage in TypeScript projects

Note: If you write your worker files in plain JS, you can configure your project by following the steps from the previous section. If you need to write them in TS, follow the steps in this section.

  1. Define a custom module for your worker's exports:
// typings/custom.d.ts
declare module "nativescript-worker-loader!*" {
  const content: any;
  export = content;
}
  1. Add the typings to references.d.ts:
// references.d.ts

/// <reference path="./typings/custom.d.ts" /> Workerloader
  1. Write a worker file:
// app/worker.ts
import "globals";

const context: Worker = self as any;

context.onmessage = msg => {
    setTimeout(() => {
        console.log("Inside TS worker...");
        (<any>global).postMessage("TS Worker");
    }, 500)
};
  1. Import and use the worker file in the following way:
// app/main.ts
import * as TsWorker from "nativescript-worker-loader!./workers/typescript.worker";

const worker = new TsWorker();
  1. Configure your webpack.config.js to use the NativeScriptWorkerPlugin.
// webpack.config.js
const { NativeScriptWorkerPlugin } = require("nativescript-worker-loader/NativeScriptWorkerPlugin");
// ...

module.exports = env => {
    // ...

    const config = {
        //...
        plugins: [
            new NativeScriptWorkerPlugin(),
            // ...
        ]
    }
}
  1. [Angular projects only] Install ts-loader:
npm i -D ts-loader
  1. [Angular projects only] Update your webpack.config.js to compile the worker files using ts-loader instead of the ngtools/webpack loader. The following code assumes that all your worker files are named in the format - some-name.worker.ts. You can use a different naming convention but you have to setup the webpack loaders to also follow it.
// webpack.config.js

module.exports = env => {
    // ...

    const config = {
        //...
        module: {
            rules: [
                // Compile TypeScript files with ahead-of-time compiler.
                {
                    test: /.ts$/, exclude: /.worker.ts$/, use: [
                        "nativescript-dev-webpack/moduleid-compat-loader",
                        "@ngtools/webpack",
                    ]
                },

                // Compile Worker files with ts-loader
                { test: /\.worker.ts$/, loader: "ts-loader" },
            ]
        }
    }
}

Web workers with/without webpack

Please note that the way to spawn a Worker with webpack differs from the way described in the WWW Web Workers' specification (also followed by NativeScript).

Below are a few examples on how to use workers for builds with and without webpack.

JS worker scripts

If you wrote your worker scripts in plain JavaScript, you can require them.

Usage with webpack:

const WorkerScript = require("nativescript-worker-loader!./worker-script.js");
const worker = new WorkerScript();

Usage without webpack:

// without webpack
const worker = new Worker("./worker-script.js");

Or you can use the TNS_WEBPACK global variable to find out if your app is built with webpack or not:

let worker: Worker;
if (global["TNS_WEBPACK"]) {
    const WorkerScript = require("nativescript-worker-loader!./worker-script.js");
    worker = new WorkerScript();
} else {
    worker = new Worker("./worker-script.js");
}

TS worker scripts

However, if you wrote your worker scripts with TypeScript, you cannot use the same code for both webpack builds and non-webpack builds.

Usage with webpack:

import * as WorkerScript from "nativescript-worker-loader!./worker-script";
const worker = new WorkerScript();

Usage without webpack:

const worker = new Worker("./worker-script");

Demo apps

For usage with NativeScript Angular, check out demo-angular in this repo.

For usage with NativeScript apps written in plain JavaScript, check out this repo: https://github.com/NativeScript/demo-workers.

Related docs

  1. Workers in NativeScript
  2. Webpack for NativeScript apps

worker-loader's People

Contributors

dicksmith avatar dtinth avatar frogthefrog avatar hawkrives avatar hypery2k avatar joshwiens avatar kevinzwhuang avatar kevzettler avatar michael-ciniawsky avatar peterstaev avatar pkoleva avatar simon04 avatar sis0k0 avatar sokra avatar spacek33z avatar svetoslavtsenov avatar tobek avatar tomlagier avatar trusktr avatar trysound avatar tsonevn avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.