0

This post: Can I use an ES6/2015 module import to set a reference in 'global' scope? answers the problem of "how do I make a module globally available in Webpack?" by using Webpack's ProvidePlugin:

// webpack.config.js
plugins: [
    new webpack.ProvidePlugin({
        React: "react",
    })
],

// Foo.js
class Foo extends React.Component { // React is global

But what if I want to make a global for a named export, instead of a default export? In other words, what if I want to do:

// Foo.js
class Foo extends React.Component {
    propTypes = {
        bar: PropTypes.string, // PropTypes were never imported
    }

The problem is that PropTypes is a named export, which means I'd normally import it as:

import {PropTypes} from 'react';

but I can't do that in the Webpack config:

new webpack.ProvidePlugin({
    {PropTypes}: "react", // this doesn't work
})

So, my question is: is there any way to expose a named export (eg. React's PropTypes) globally with Webpack?

P.S. I would just do it explicitly in my root JS file:

// index.js
import {PropTypes} from 'react';
global.PropTypes = PropTypes;
import 'restOfMyCode';

but that doesn't work because the imports are hoisted and occur before the global.PropTypes ever get set, so when my modules get imported there's no global.PropTypes for them to use.

Community
  • 1
  • 1
machineghost
  • 33,529
  • 30
  • 159
  • 234

1 Answers1

2

What you could do (but it's not very clean) is the following:

new webpack.DefinePlugin({
  PropTypes: 'require("react").PropTypes',
})

This will make webpack simply replace every mention of PropTypes (in that exact case) with the react require call and access it's child PropTypes. It's not the most efficient thing, but it will do what you need it to!

Another solution would be to simply export PropTypes yourself as the default export in another file, then pass that to ProvidePlugin with an absolute path.

In a file (for example proptypes.js):

import { PropTypes } from 'react';
export default PropTypes;

And then in your webpack config:

new webpack.ProvidePlugin({
    PropTypes: require('path').resolve('../src/proptypes.js'), // absolute path here, otherwise the require might fail since a relative path is not always the same depending on where PropTypes are used
})
Ambroos
  • 3,456
  • 20
  • 27