Skip to content

Vite is designed for front-end React development, so the notion of Node.js' process module doesn't really apply. How then does one create and access process.env environment variables? Thankfully it's surprisingly straightforward. Firstly create a .env file in your project root and put, say, the following into it:

BASE_URL = https://some.url.here

Then you can access that via Vite's own env variables object import.meta.env:

...
const url = import.meta.env.BASE_URL
...

Except that will not work. Here url will be undefined. To ensure that Vite collects and env variables meant for it, prefix your var names with VITE_:

VITE_BASE_URL = https://some.url.here
...
const url = import.meta.env.VITE_BASE_URL
...

If you missed the introductory post, please start there. Otherwise...

Why write loads of boilerplate when there are third-party libraries you can just plug in? Well there are reasons of course, but perhaps in your case they are not compelling enough, and the simplicity of a library appeals. If so, you can use comlink. Install it.

npm i comlink

Or the equivalent in yarn. Then, if you are using Vite like me.

npm i -D vite-plugin-comlink

Or the equi... Then configure Vite to use the plugin.

import { defineConfig } from "vite";
import { comlink } from "vite-plugin-comlink";

import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), comlink()],
  worker: {
    plugins: () => comlink(),
  },
});
/// <reference types="vite/client" />
/// <reference types="vite-plugin-comlink/client" />

And you are good to go. Back in your workers directory create a new file called comlink-worker.ts to hold our slow calculation.

export const slowCalculation = () => {
  const result = new Array<number>(30_000_000)
    .fill(0)
    .map((value, index) => value + index)
    .reduce((total, value) => total + value, 0);
  return result;
};

And thanks to the magic of other people's coad, the amount you have to write to run it is minimal.

import { useState } from "react";

export const App = () => {
  const [n, setN] = useState(0);

  setTimeout(() => setN(100 + Math.round(Math.random() * 899)), 100);

  const workerInstance = new ComlinkWorker<
    typeof import("./workers/comlink-worker")
  >(new URL("./workers/comlink-worker", import.meta.url));

  const handleOnClick = async () => {
    console.log("start comlink worker");
    const result = await workerInstance.slowCalculation();
    console.log("comlink worker result", result);
  };

  return (
    <>
      <p>{n}</p>
      <button onClick={() => handleOnClick()}>Start web worker</button>
    </>
  );
};

export default App;

There are other ways to run a web worker in React

  1. via the DedicatedWorkerGlobalScope; or
  2. with a blob.

Part 1: Introduction

Given that JavaScript is single-threaded, how does one run a processor-intensive script without locking up the UI? With something called a Web Worker. which runs in a separate context to the current window. Like any JavaScript app, React apps can utilise web workers, and there are several ways of doing it. I will show you three different ways, so you can choose which is best for you:

  1. via the DedicatedWorkerGlobalScope;
  2. with a blob; or
  3. with the Comlink library.

Firstly create your own React spike, by whatever means suits you, create-react-app or Vite, or something else. Call it whatever you want. If it matters: I used Vite and called it web-worker. You will need your root app component plus whatever supports it. For me that App.tsx and these files:

index.html
main.tsx
index.css
(and App.tsx)

The first three look like this:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Three methods of running Web Workers in React</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
import "./index.css";

import React from "react";
import ReactDOM from "react-dom/client";

import App from "./App.tsx";

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
#root {
  margin: 0 auto;
}

body {
  margin: 0;
  padding: 20px;
}

Our web worker will run a background process that will not render anything to the screen, but we will put something on the screen to visualise it blocking the thread: a setTimeout function which will render a random integer to the screen ten times a second.

import { useState } from "react";

export const App = () => {
  const [n, setN] = useState(0);

  setTimeout(() => setN(100 + Math.round(Math.random() * 899)), 100);

  return (
    <>
      <p>{n}</p>
    </>
  );
};

export default App;

Next lets add a button which, when clicked, will run a slow calculation.

import { useState } from "react";

export const App = () => {
  const [n, setN] = useState(0);

  setTimeout(() => setN(100 + Math.round(Math.random() * 899)), 100);

  const slowCalculation = () => {
    const result = Array(30_000_000)
      .fill(1)
      .map((value, index) => value + index)
      .reduce((total, value) => total + value);
    self.postMessage(result);
  };

  return (
    <>
      <p>{n}</p>
      <button
        onClick={() => {
          console.log("start slow calculation...");
          const result = slowCalculation();
          console.log("slow calculation result:", result);
        }}
      >
        Press
      </button>
    </>
  );
};

export default App;

When clicked, slowCalculation hogs the processor and prevents setTimeout from updating the value of n. Clearly this is *cough* 'suboptimal.'

This is where a web worker can help, by farming that intensive process outside of the single Javascript thread. Now let's look at three ways of doing this:

  1. via the DedicatedWorkerGlobalScope;
  2. with a blob; or
  3. with the Comlink library.