gatsby-plugin-workerize-loader
v2.1.0
Published
Integrate workerize-loader with GatsbyJS
Downloads
6,161
Maintainers
Readme
gatsby-plugin-workerize-loader
A Gatsby plugin to integrate web workers into your GatsbyJS app via workerize-loader.
Install
Latest 2.0.0 version is compatible with Gatsby 3 and Webpack 5.
With Yarn:
yarn add gatsby-plugin-workerize-loader -D
Or with npm:
npm install --save-dev gatsby-plugin-workerize-loader
For Gatsby 2, please use version 1.5.0.
yarn add [email protected] -D
Or with npm:
npm install --save-dev [email protected]
Usage
Add plugin to gatsby-config.js
plugins: ['gatsby-plugin-workerize-loader']
Create a worker file with suffix .worker.js
e.g. search.worker.js
.
// search.worker.js
export async function search(searchInput) {
// expensive search procedure...
return searchResults
}
Import and instantiate the web worker in your source file. One caveat is web worker only works in browser environment.
// searchWorker.js
import SearchWorker from 'path/to/search.worker.js'
const searchWorker = typeof window === 'object' && new SearchWorker()
export default searchWorker
Use it in your component
// SearchComponent.js
import searchWorker from "path/to/seachWorker.js";
function SearchComponent() {
useEffect(() => {
searchWorker.search(searchInput).then(
searchResults => // do something with search results
);
}, [searchInput]);
}
Recipes
Lazy initialization
Worker code is only downloaded and parsed when you first instantiate Worker i.e. new Worker()
. Automatic code-splitting 🔥🔥🔥.
With useRef within a component.
// SearchComponent.js
import SearchWorker from "path/to/search.worker.js";
function SearchComponent() {
const searchWorkerRef = useRef(null);
function getSearchWorker() {
if (!searchWorkerRef.current) {
searchWorkerRef.current = new SearchWorker();
}
return searchWorkerRef.current;
}
useEffect(() => {
getSearchWorker().search(searchInput).then(
searchResults => // do something with search results
);
}, [searchInput]);
}
Or anywhere in your app.
// getSearchWorker.js
import SearchWorker from 'path/to/search.worker.js'
let searchWorker
export default function getSearchWorker() {
if (!searchWorker) {
searchWorker = new SearchWorker()
}
return searchWorker
}
// anywhere.js
import getSearchWorker from "path/to/getSearchWorker.js";
function someOperation (searchInput) {
getSearchWorker().search(searchInput).then(
searchResults => // do something with search results
);
// remaining steps
}
License
MIT