Webpack + `create-react-app` | ProvidePlugin Not Loading React as a Module

Viewed 3210

* Note: I barely know anything about Webpack.

I want to load the react node module and other modules in Webpack via ProvidePlugin to have global access to them.

I created a create-react-app and ran eject and got access the pre-defined configuration for Webpack create-react-app provides.

I read this post about loading react globally via PluginProvidor and read about PluginProvidor itself in the Webpack docs, where the latter states:

By default, module resolution path is current folder (./**) and node_modules

Based on that, in webpack.config.js, in plugins, I added the following PluginProvidor:

...
plugins: [
  new webpack.ProvidePlugin(
    {
      React: 'react'
    }
  )
]
...

But it didn't work - in a JSX file when I call React (e.g class MyComponent extends React.Component { ... }) I get an error that says that React isn't defined (and also a React-specfic error that React must be defined in JSX files).

Why doesn't it work? As far as I understand, I'm giving the same identifier I call in my JSX file, and like I mentioned, according to the Webpack docs, to the path of the react module in node_modules - both as required for it to work.

My configuation file: webpack.config.js

1 Answers

It's not a good idea to use ProvidePlugin, and even worse is to eject your CRA.

Instead of ProvidePlugin use globals:

// globals.js
import React from 'react';

window.React = React;

and then import './globals'

import './globals';

// no need import React
import ReactDOM from 'react-dom';
...

For adding plugins to CRA web pack refer to react-app-rewired.

Example of adding a plugin:

/* config-overrides.js */
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = function override(config, env) {
  if (!config.plugins) {
    config.plugins = [];
  }
  config.plugins.push(new MonacoWebpackPlugin());
  return config;
};

Demo:

Edit modest-meninsky-brb7y

Related