在Node.js中动态需求

时间:2018-12-28 22:41:28

标签: node.js reactjs

am试图从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;

我想念什么?

1 个答案:

答案 0 :(得分: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} />

这样更有效,并且可以极大地减小捆绑包的大小(因为您不需要包括一堆甚至都不需要使用的额外图标)。

相关问题