worker-inlinify transforms separate web worker script reference into inline script using syntax: new Worker(window.URL.createObjectURL(new Blob(["/* Web Worker code here */"])))
.
You can install it globally to use the CLI everywhere.
npm install worker-inlinify -g
Or just install within your project.
npm install worker-inlinify --save
worker-inlinify is available as a global command if you installed it globally. It will read all *.js
files from the current working directory and inlinify any external web worker references like new Worker("worker.js")
if the external web worker script can be found.
For example, you have following files in the home directory.
-
home/main.js
var worker = new Worker('src/worker.js'); var fakeWorker = new Worker('non-existing-worker.js'); eval('new Worker("src/worker.js")');
-
home/src/worker.js
(function(){ console.log('Hi from worker.js'); })();
After running worker_inlinify
command in home directory, the main.js will be overwritten to:
var worker = new Worker(window.URL.createObjectURL(new Blob(["(function(){\r\n console.log(\'Hi from worker.js\');\r\n})();"])));
var fakeWorker = new Worker('non-existing-worker.js');
eval('new Worker(window.URL.createObjectURL(new Blob([\"(function(){\\r\\n console.log(\\\'Hi from worker.js\\\');\\r\\n})();\"])))');
If you don't want to install it globally, worker-inlinify is also available from npm scripts, you can define it in a custom script like below in your package.json.
{
"scripts": {
"inlinify": "worker-inlinify"
}
}
And npm run inlinify
will do the same trick.
If you have the following code snippet, you would get an error: SyntaxError: Identifier 'a' has already been declared (3:4) when running worker-inlinify
. This is because worker-inlinify uses Acorn as the JavaScript parser to parse your JS code and Acorn will raise a SyntaxError
object when encountering a syntax error.
var worker = new Worker('src/worker.js');
let a = 'a';
let a = 'a';
You can use worker-inlinify --loose
to overcome this, but it is not recommended.
Description: Inlinify the given source code.
Parameter | Type | Description |
---|---|---|
source | String | The source string to be inlinified. |
The inlinified script.
Description: Inlinify the given JS file, the file must have a "js" extension name.
Parameter | Type | Description |
---|---|---|
file | String | The JS file path to be inlinified |
No return value, the JS file will be overwritten with the inlinified result.
Description: The path where workerInlinify finds the external web worker scripts.
The default contextPath is the current node working directory. You can set to a custom path where workerInlinify can find the external web worker scripts.
Description: Whether to use an error-tolerant parser.
The default value is false. If you encounter a SyntaxError
when inlinifying the script, you may either fix the Syntax error in your script or set this value to true to solve it.