This package has been deprecated

Author message:

Next.js now has built-in support for Web Workers: https://github.com/vercel/next.js/tree/canary/examples/with-web-worker

@zeit/next-workers

1.0.0 • Public • Published

Next.js + Web Workers

Use Web Workers in your Next.js project using import.

Installation

npm install --save @zeit/next-workers worker-loader

or

yarn add @zeit/next-workers worker-loader

Usage

Create a next.config.js in your project

// next.config.js
const withWorkers = require('@zeit/next-workers')
module.exports = withWorkers()

Optionally you can add your custom Next.js configuration as parameter

// next.config.js
const withWorkers = require('@zeit/next-workers')
module.exports = withWorkers(
  webpack(config, options) {
    return config
  }
})

You can also pass overriding options to worker-loader using workerLoaderOptions

// next.config.js
const withWorkers = require('@zeit/next-workers')
module.exports = withWorkers({
  workerLoaderOptions: { inline: true },
})

Web Worker files are identified by the .worker.js extension

Because Workers are transpiled with worker-loader you can import dependencies just like other project files. See the worker-loader documentation for examples

// example.worker.js
self.addEventListener('message', (event) => console.log('Worker received:', event.data))
self.postMessage('from Worker')

The Worker can then be imported like a normal module and instantiated

// pages/example.js
import React from 'react';

import ExampleWorker from '../example.worker';

export default class extends React.Component {
  state = { latestMessage: null }
  componentDidMount() {
    // Instantiate the Worker
    this.worker = new ExampleWorker()
    this.worker.postMessage('from Host')
    this.worker.addEventListener('message', this.onWorkerMessage)
  }
  componentWillUnmount() {
    // Close the Worker thread
    this.worker.terminate()
  }
  onWorkerMessage = (event) => this.setState({ latestMessage: event.data })
  render() {
    return <h1>Message from Worker: {this.state.latestMessage}</h1>
  }
}

Readme

Keywords

none

Package Sidebar

Install

npm i @zeit/next-workers

Weekly Downloads

677

Version

1.0.0

License

MIT

Unpacked Size

4.21 kB

Total Files

4

Last publish

Collaborators

  • gdborton
  • matheuss
  • matt.straka
  • nick.tracey
  • zeit-bot
  • vercel-release-bot