Search code examples
reactjstypescriptglobalmaterial-uireferenceerror

Material-UI + TypeScript gives ReferenceError: global is not defined


I have executed

npm install --save react react-dom @material-ui/core
npm install --save-dev webpack webpack-cli typescript ts-loader @types/react @types/react-dom

and transpiled main.tsx:

import * as React from "react";
import * as ReactDOM from "react-dom";
import Button from '@material-ui/core/Button';

window.onload = () => { ReactDOM.render(<Button />, document.getElementById("app")) };

This file was successfully transpiled, but I had a ReferenceError in node_modules/jss/lib/utils/escape.js:6

var CSS = global.CSS; // ReferenceError: global is not defined

How can I suppress this error?

This is my webpack.config.js:

module.exports = {
    mode: "development",
    entry: __dirname + "/src/main.tsx",
    output: {
        path: __dirname + "/www",
        filename: "bundle.js",
    },
    devtool: "source-map",
    module: {
        rules: [ {test: /\.tsx?$/, use: "ts-loader"} ]
    },
    resolve: {
        extensions: [".ts", ".tsx", ".js"]
    },
    target: "node"
};

Solution

  • you have target: "node"

    globals like global and require are provided by the environment. Unless otherwise specified, Webpack assumes a browser environment and rewrites global to point to window.

    You could either remove target: 'node' from your config, or explicitly enable global rewriting by adding node: {global: true} to your config object.