webpack 动态导入React Material UI图标

5anewei6  于 12个月前  发布在  Webpack
关注(0)|答案(2)|浏览(121)

主要的想法是只在需要的时候导入react材质的UI图标,或者在编译时我们不知道图标名称的时候动态导入。(让我们保证我们有有效的图标名称)。
我的方法是使用带有动态路径的require语句:

const IconComponent = require(`@material-ui/icons/${icon}`).default;

字符串
这很好,但出现了一些警告。
./node_modules/@material-ui/icons/utils/Uplink SvgIcon.d.ts 3:8模块解析失败:意外的标记(3:8)您可能需要适当的加载程序来处理此文件类型。|从“@material-ui/core/SvgIcon”导入SvgIcon;| declare function SvgIcon(path:React.ReactNode,DisplayName:string):typeof SvgIcon;||导出默认值“”SvgIcon“;
./node_modules/@material-ui/icons/index.d.ts 4:5 Module parse failed:Unexpected token(4:5)您可能需要适当的加载程序来处理此文件类型。|从“@material-ui/core/SvgIcon”导入SvgIcon;|
type SvgIconComponent = typeof SvgIcon;||export const_parameter_alarm:SvgIconComponent;
我的问题是:我们如何避免这些警告并以适当的方式进行动态导入?

z4bn682m

z4bn682m1#

你可以为它创建一个钩子,如下所示。

//1) $ npm i string-similarity
import * as icons from '@material-ui/icons'
import stringSimilarity from 'string-similarity'

function useIcons(word) {
  const iconsNames = Object.keys(icons)

  var matches = stringSimilarity.findBestMatch(word, iconsNames)
  const bestMathch = matches.bestMatch.target
  const Icon = icons[bestMathch]
  return Icon
}
export default useIcons
import Icon from './myCustomeHooks/useIcons'
// other file like
const Icon =  useIcons('tablechart')  // not the name should start with capital letter in case you use reactjs

// now you can use the icon as you like
<Icon/>

请注意import * as icons from '@material-ui/icons'const * as icons = require('@material-ui/icons').default;相同

选项2

import React from 'react';
import { loadCSS } from 'fg-loadcss';
import { makeStyles, createStyles, Theme } from '@material-ui/core/styles';
import { green } from '@material-ui/core/colors';
import Icon from '@material-ui/core/Icon';

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      '& > .fa': {
        margin: theme.spacing(2),
      },
    },
  }),
);

export default function FontAwesome() {
  const classes = useStyles();

  React.useEffect(() => {
    const node = loadCSS(
      'https://use.fontawesome.com/releases/v5.12.0/css/all.css',
      document.querySelector('#font-awesome-css'),
    );

    return () => {
      node.parentNode!.removeChild(node);
    };
  }, []);

  return (
    <div className={classes.root}>
      <Icon className="fa fa-plus-circle" />
      <Icon className="fa fa-plus-circle" color="primary" />
      <Icon className="fa fa-plus-circle" color="secondary" />
      <Icon className="fa fa-plus-circle" style={{ color: green[500] }} />
      <Icon className="fa fa-plus-circle" fontSize="small" />
      <Icon className="fa fa-plus-circle" style={{ fontSize: 30 }} />
    </div>
  );
}

nwnhqdif

nwnhqdif2#

一是

(async () => {
  if (somethingIsTrue) {
    const { default: myDefault, foo, bar } = await 
import('/modules/my-module.js');
  }
})();

字符串
二方法是

let module = await import('/modules/my-module.js');


你可以调整的一个很好的例子是

const main = document.querySelector("main");
for (const link of document.querySelectorAll("nav > a")) {
 link.addEventListener("click", e => {
 e.preventDefault();

 import('/modules/my-module.js')
   .then(module => {
     module.loadPageInto(main);
   })
    .catch(err => {
     main.textContent = err.message;
    });
 }

相关问题