网站搜索

reactjs - 模块未找到:错误:在向 CRA 应用添加 TypeScript 时无法解析 TypeScript 文件


我正在尝试将 typescript 添加到我的项目中,并用 typescript 编写新的组件。我按照文档操作,但出现了这个错误:
无法解析 [typescript 文件]

即使是新的 create-react-app 项目也会发生这种情况。
根据 CRA 关于向现有 Create React App 项目添加 typescript 的文档,首先,我们必须安装 typescript 和 类型定义文件:

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

快完成了!
将一个 js/jsx 文件重命名为 tsx 并重启你的开发服务器!

为简便起见,我正在创建一个名为 test.tsx 的 typescript 文件,其中包含 Test 组件:

export default function Test(){
    return (
        <div>this is test to see typescirpt</div>
    )
}

并将其导入到 main.js 并进行渲染:

import Test from "./test";

function App() {
  return (
    <div className="App">
      <Test />
    </div>
  );
}

export default App;

现在我正在重新启动开发服务器(我用 CRTL+c 关闭了之前的服务器),使用 npm start。
我收到这个错误:

Compiled with problems:

ERROR in ./src/App.js 4:0-26

Module not found: Error: Can't resolve './test' in '/home/g/w/ts/test_adding_ts/src'

我使用了一个全新的 create-react-app 项目,按照文档操作后,看到这个错误。(为什么?)
这是我安装的依赖项:

  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.0.1",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.4.1",
    "@types/node": "^17.0.24",
    "@types/react": "^18.0.5",
    "@types/react-dom": "^18.0.1",
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-scripts": "5.0.1",
    "typescript": "^4.6.3",
    "web-vitals": "^2.1.4"
  },

答案#1

你在根目录中创建了配置文件 tsconfig.json 吗?我在问题中没看到提到这一点。

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

如果未创建,您可以在与 package.json 同级的根目录中创建一个并粘贴上述配置。或者如果已经创建,您可以用上述配置替换现有配置并重新检查。

答案#2

CRA 文档指南在按步骤操作时是可行的,但在说“将任何文件重命名为 TypeScript 文件”时就非常棘手。根据 create-react-app 的源代码,要使用 TypeScript,你的应用应该包含 ./tsconfig.json 文件。

如指南所述的简单重命名,仅适用于 ./src/index.(js|ts|jsx|tsx) 文件,但所有导入都会失败,因为 create-react-app 配置 webpack 排除了所有 TypeScript 文件。

最小的 ./tsconfig.json 文件,根据我个人检查 CRA 版本 5.0.1,如下所示:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "jsx": "react"
  }
}

相关文章