首页 > 解决方案 > 当我尝试从库中导入 TypeScript 接口时出现 Webpack“未找到模块”错误?

问题描述

我有一个 React 项目,我正在将它转换为 TypeScript,所以新组件是 TypeScript,而旧组件是 JavaScript。我还通过它的 React 组件介绍了 FontAwesome。

一切正常,直到我导入一个fontawesome-common-types导致编译错误的接口。

这一直有效,直到我取消注释第一行:

// import { IconDefinition } from '@fortawesome/fontawesome-common-types';
import * as React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faAngleRight } from '@fortawesome/pro-solid-svg-icons';

export type Props = {
  links: {
    text: string;
    icon: any; // This is what I need IconDefinition for
    url: string;
  }[];
};

const MyComponent: React.FC<Props> = ({ links }) => {
  return (
    <ul>
      {
        links.map((link,index)=>(
          <li key={index}>
            <a href={link.url}>
              {link.text}
              <FontAwesomeIcon icon={link.icon} />
            </a>
          </li>
        ))
      }
    </ul>
  );
};

此时我收到此错误:

./src/components/MyComponent/MyComponent.tsx 中的错误找不到模块:错误:无法解析“/Users/MYNAME/projects/PROJECT/src/components/MyComponent”中的“@fortawesome/fontawesome-common-types”

在 tsconfig.json 中:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "strictNullChecks":  true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve"
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "**/*.ts",
    "**/*.tsx"
  ]
}

标签: reactjstypescriptwebpackfont-awesome

解决方案


推荐阅读