【问题标题】:Dynamic require in nodejs & reactnodejs中的动态需求和反应
【发布时间】:2018-12-28 22:41:27
【问题描述】:

我正在尝试从 react-icons-kit 动态导入图标并引发此错误:

 Module not found: Can't resolve 'enzyme' in 'G:\my-app\node_modules\react-icons-kit'

我已经尝试了一个小时,没有任何结果。


我的代码:

import React from 'react';
import { Icon } from 'react-icons-kit';

const Button = ({ icon = 'home', library = "fa", children, ...props }) => {

    if (icon) {
        var svg = require('react-icons-kit/' + library + '/' + icon);
    }

    return (
        <button className={classes} {...props}>
            {children}
            <Icon icon={svg}/>
        </button>
    );
};

export default Button;

我错过了什么?

【问题讨论】:

    标签: node.js reactjs


    【解决方案1】:

    您不能以这种方式动态导入,因为您的捆绑器需要在构建应用程序时了解所有依赖项。如果您绝对需要使用此动态路由,您可以使用require.context 加载整个文件夹,然后从中动态加载它们:

    import React from 'react';
    import { Icon } from 'react-icons-kit';
    const iconRequire = require.context('react-icons-kit/', true);
    
    const Button = ({ icon = 'home', library = "fa", children, ...props }) => {
    
        if (icon) {
            var svg = iconRequire('./' + library + '/' + icon);
        }
    
        return (
            <button className={classes} {...props}>
                {children}
                <Icon icon={svg}/>
            </button>
        );
    };
    
    export default Button;
    

    但是,将实际图标传递给 Button 类会更有效:

    import homeIcon from 'react-icon-kit/fa/home';
    
    // Call it below, and drop the strings all together:
    
    <Button icon={homeIcon} />
    

    这更有效,并且会大大减少你的包大小(因为你不需要包含一大堆你甚至可能不会使用的额外图标)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-30
      • 1970-01-01
      • 2019-04-01
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      相关资源
      最近更新 更多