Webpack:如何在全局范围内使用命名导出
问题描述:
这篇文章:Can I use an ES6/2015 module import to set a reference in 'global' scope?回答了“我如何在Webpack中创建全局模块?”这个问题。使用的WebPack的ProvidePlugin
:Webpack:如何在全局范围内使用命名导出
// webpack.config.js
plugins: [
new webpack.ProvidePlugin({
React: "react",
})
],
// Foo.js
class Foo extends React.Component { // React is global
但是,如果我想打一个全球性的名为出口什么,而不是默认的导出,?换句话说,如果我想要做什么:
// Foo.js
class Foo extends React.Component {
propTypes = {
bar: PropTypes.string, // PropTypes were never imported
}
的问题是,PropTypes
是一个命名的出口,这意味着我通常导入为:
import {PropTypes} from 'react';
,但我不能这样做在的WebPack配置:
new webpack.ProvidePlugin({
{PropTypes}: "react", // this doesn't work
})
所以,我的问题是:有什么办法可以暴露了一个名为全球出口用的WebPack(例如作出反应的PropTypes
)?
P.S.我只是做了明确我的根JS文件:
// index.js
import {PropTypes} from 'react';
global.PropTypes = PropTypes;
import 'restOfMyCode';
但是,这并不工作,因为进口悬挂和global.PropTypes
曾经得到集之前进行的,所以当我的模块获得进口没有global.PropTypes
他们使用。
答
你能做什么(但不是很干净)如下:
new webpack.DefinePlugin({
PropTypes: 'require("react").PropTypes',
})
这将使的WebPack只需更换的PropTypes
每提(在精确的情况下)与反应需要调用和访问它的子PropTypes。这不是最有效的,但它会做你需要的!
另一种解决方案是简单地将PropTypes自己导出为另一个文件中的默认导出,然后将它传递给ProvidePlugin一个绝对路径。
在一个文件(例如proptypes.js):
import { PropTypes } from 'react';
export default PropTypes;
然后在您的WebPack配置:
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
})