我是否需要从导入并添加到库中重新列出我的所有React Font Awesome图标?

时间:2019-04-30 16:14:37

标签: reactjs icons font-awesome react-font-awesome

不得不将所有导入的图标重新输入到library.add函数中似乎很麻烦(并且像步枪一样)。有办法解决这个问题吗?

// font-awesome-library.js

import { library } from '@fortawesome/fontawesome-svg-core'
import {
  faChartBar, faFileAlt, faBalanceScale, faUser, faFutbol, faBuilding,
  faAddressBook, faChartLine, faDatabase, faServer, faLink, faCloudUpload,
  faClipboard, faSlidersH, faChartBar, faUsers
} from '@fortawesome/pro-solid-svg-icons'
import { faFortAwesome} from '@fortawesome/free-brands-svg-icons';

// Re-listing these below seem tedious..
library.add(
  faChartBar, faFileAlt, faBalanceScale, faUser, faFutbol, faBuilding,
  faAddressBook, faChartLine, faDatabase, faServer, faLink, faCloudUpload,
  faClipboard, faSlidersH, faChartBar, faUsers, faFortAwesome, 
);

此外,如果我输入错误(或使用错误的名称,例如faBarChart而不是faChartBar),我在react-fontawesome中会遇到无用的错误:TypeError: Cannot read property 'prefix' of undefined:(

1 个答案:

答案 0 :(得分:0)

我将font-awesome-library.js重构为:

// font-awesome-library.js

import { library } from '@fortawesome/fontawesome-svg-core'
import * as icons from './font-awesome-icons';

Object.keys(icons).forEach(key => {
  try {
    library.add(icons[key]);
  } catch (err) {
    console.log(key);
    debugger; // eslint-disable-line
    throw err;
  }
});

只需在font-awesome-icons.js中枚举一次图标即可:

// font-awesome-icons.js

export {
  faChartBar, faFileAlt, faBalanceScale, faUser, faFutbol, faBuilding,
  faAddressBook, faChartLine, faDatabase, faServer, faLink, faCloudUpload,
  faClipboard, faSlidersH, faChartPie, faUsers
} from '@fortawesome/pro-solid-svg-icons'
export { faFortAwesome} from '@fortawesome/free-brands-svg-icons';

此外,通过将它们导入为对象({faChartBar, faFileAlt, /*...*/}),我可以确切地知道(尝试导入的图标中)哪个图标被错误命名,从而解决了另一个问题。