reactjsbabeljs

ReferenceError: $RefreshReg$ is not defined


In a CRA based React app I get this error in a webworker file (all code is using Typescript) when I import files that are also imported by normal application code (normal === non-worker) and run the app using the babel dev server in debug mode.

Searching for this error brings me to various module specific issue reports/solutions, which I cannot use, however. But it's clear that this is a React hot reloading problem and I wonder how to solve it, as it keeps me from using my app code also in web workers.

My dev dependencies are:

    "devDependencies": {
        "@babel/core": "^7.12.10",
        "@babel/preset-env": "^7.11.11",
        "@babel/preset-typescript": "^7.12.7",
        "@testing-library/react": "^11.2.3",
        "@types/classnames": "^2.2.11",
        "@types/color": "^3.0.1",
        "@types/d3": "^6.2.0",
        "@types/history": "4.7.8",
        "@types/jest": "^26.0.20",
        "@types/lodash": "^4.14.168",
        "@types/node": "^14.14.22",
        "@types/react": "^17.0.0",
        "@types/react-dom": "^17.0.0",
        "@types/react-test-renderer": "^17.0.0",
        "@types/react-window": "^1.8.2",
        "@types/resize-observer-browser": "^0.1.5",
        "@types/selenium-webdriver": "^4.0.11",
        "@types/topojson": "^3.2.2",
        "@types/uuid": "^8.3.0",
        "@types/ws": "^7.4.0",
        "@typescript-eslint/eslint-plugin-tslint": "^4.14.0",
        "acorn": "^8.0.5",
        "antlr4ts-cli": "^0.5.0-alpha.4",
        "eslint": "^7.18.0",
        "eslint-plugin-flowtype": "^5.2.0",
        "eslint-plugin-import": "^2.22.1",
        "eslint-plugin-jsdoc": "^31.3.3",
        "eslint-plugin-jsx-a11y": "^6.4.1",
        "eslint-plugin-prefer-arrow": "^1.2.2",
        "eslint-plugin-react": "^7.22.0",
        "eslint-plugin-react-hooks": "^4.2.0",
        "identity-obj-proxy": "^3.0.0",
        "jest": "26.6.0",
        "jest-transform-stub": "^2.0.0",
        "jest-websocket-mock": "^2.2.0",
        "mock-socket": "^9.0.3",
        "monaco-editor-webpack-plugin": "^1.9.1",
        "monaco-typescript": "^4.2.0",
        "raw-loader": "^4.0.2",
        "react-app-rewired": "^2.1.8",
        "react-scripts": "^4.0.3",
        "react-test-renderer": "^17.0.1",
        "selenium-webdriver": "^4.0.0-beta.1",
        "ts-jest": "^26.5.2",
        "tslint": "^6.1.3",
        "typescript": "^4.1.3",
        "typescript-eslint-parser": "22.0.0",
        "webdriver-manager": "^12.1.8",
        "webpack": "4.44.2",
        "webpack-bundle-analyzer": "^4.4.0",
        "worker-loader": "^3.0.8",
        "ws": "^7.4.3"
    },

The only promising solution I also could apply is: https://github.com/pmmmwh/react-refresh-webpack-plugin/issues/176#issuecomment-683150213, but it didn't help. I still get the same error. My web worker code is:

/* eslint-disable no-restricted-globals */
/* eslint-disable no-eval */
/* eslint-disable @typescript-eslint/no-unused-vars */

(window as any).$RefreshReg$ = () => {/**/};
(window as any).$RefreshSig$ = () => () => {/**/};

import { ShellInterfaceSqlEditor } from "../../supplement/ShellInterface";
import { PrivateWorker, ExecutionResultType, IConsoleWorkerData } from "./console.worker-types";

const backend = new ShellInterfaceSqlEditor();
const ctx: PrivateWorker = self as any;

The further discussion there about changing the babel loader config is unfortunately beyond me, as I don't configure that myself (what I'm using, however, is react-app-rewired to configure some custom loaders).

What else could I try to fix the issue?


Solution

  • I tried many of the solutions in this answer and in various Github issues, but none of them resolved the issue for me. Eventually I found a solution via the Webpack sideEffects optimization and config!

    tl;dr:

    • Ensure your Webpack config has an object optimization set and that the optimization object has an attribute sideEffects set to true. Seems like nx and potentially cra or craco defaults this to false, leading to unused React components being imported in WebWorker bundles if they're exported as part of a "barrel" file
    • If you're importing your own shared ui package which exports React components and some non-React components, then you need to specify the sideEffects config in your package's package.json file to ensure that the React components are marked as "pure" and safe to prune. See below for more details

    After inspecting the bundles of my WebWorker, I realized that some React components were being bundled into the worker bundle from worker-loader, even though they weren't being used in the worker. At least one of these cases was happening in our app because we have a shared package which contained some React components and other normal TS utils.

    Our WebWorker was importing a value (named export) from this package and for some reason, the entire package was being included in the WebWorker – including the React components that were not being used anywhere! The React Fast Refresh plugin (which is installed / used by CRA by default) then was augmenting our WebWorker bundle with the changes necessary to support hot refresh / reloading (calls to $RefreshReg$ and co).

    Some Github issues regarding this problem referenced a Webpack tree shaking optimization called sideEffects, which you can read more about at https://webpack.js.org/guides/tree-shaking/. Here's the relevant bit:

    The new webpack 4 release expands on this capability with a way to provide hints to the compiler via the "sideEffects" package.json property to denote which files in your project are "pure" and therefore safe to prune if unused.

    In your package's package.json, you can either specify "sideEffects": false to mark the whole package as "pure" and safe to prune if unused, or you can specify the specific exports / paths that do have side effects, eg for us:

      "sideEffects": [
        "./src/styles/*"
      ],
    

    However, setting this value didn't work for our app immediately, which was confusing. Eventually, I ran into a thread about this for nx where a very helpful comment noted that their Webpack config was disabling the sideEffects optimization for Webpack: (https://github.com/nrwl/nx/issues/9717#issuecomment-1163533981)

    I found that Nx is passing optimization: { sideEffects: false } to webpack, which explicitly turns off tree shaking regardless of your package.json contents. The library that was not being tree shaken in my original issue (lodash-es) already has it's own package.json where it specifies the required setting to facilitate optimal tree shaking, however Nx was turning off tree shaking in Webpack globally, so that it doesn't happen at all for any library or any code in the project.

    I tried explicitly setting webpackConfig.optimization.sideEffects = true in my app and boom! Issue resolved, React components being excluded from the WebWorker bundle.