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.