【问题标题】:Webpack: How can I use a named export in the global scopeWebpack:如何在全局范围内使用命名导出
【发布时间】:2023-03-12 03:25:01
【问题描述】:

这篇文章:Can I use an ES6/2015 module import to set a reference in 'global' scope? 回答了“如何使模块在 Webpack 中全局可用?”的问题。通过使用 Webpack 的 ProvidePlugin:

// 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 全局公开命名导出(例如 React 的 PropTypes)?

附:我会在我的根 JS 文件中明确地这样做:

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

但这不起作用,因为导入被提升并发生在global.PropTypes 设置之前,所以当我的模块被导入时,没有global.PropTypes 可供他们使用。

【问题讨论】:

    标签: webpack global-variables


    【解决方案1】:

    你可以做的(但不是很干净)如下:

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

    这将使 webpack 只需将 PropTypes 的所有提及(在这种情况下)替换为 react require 调用并访问它的子 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
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-03
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多