2016-11-16 27 views
0

這篇文章:Can I use an ES6/2015 module import to set a reference in 'global' scope?回答了「我如何在Webpack中創建全局模塊?」這個問題。使用的WebPack的ProvidePluginWebpack:如何在全局範圍內使用命名導出

// 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他們使用。

回答

1

你能做什麼(但不是很乾淨)如下:

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 
}) 
相關問題