kan*_*256 16 typescript reactjs webpack create-react-app
我正在尝试添加typescript到我的项目中并使用打字稿编写新组件。我按照文档进行操作,但出现此错误:
can't resolve [the typescript file]
即使是新create-react-app项目也会发生这种情况。
根据CRA 文档添加typescript到现有的 Create React App 项目,首先,我们必须typescript安装type definition files:
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
Run Code Online (Sandbox Code Playgroud)
快完成了!
将文件重命名js/jsx为tsx并重新启动您的开发服务器!
为简单起见,我创建一个typescript名为test.tsx包含该Test组件的文件:
export default function Test(){
return (
<div>this is test to see typescirpt</div>
)
}
Run Code Online (Sandbox Code Playgroud)
并将其导入main.js并渲染:
import Test from "./test";
function App() {
return (
<div className="App">
<Test />
</div>
);
}
export default App;
Run Code Online (Sandbox Code Playgroud)
现在我正在重新启动开发服务器(我用 关闭了前一个服务器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'
Run Code Online (Sandbox Code Playgroud)
我使用了一个新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"
},
Run Code Online (Sandbox Code Playgroud)
bna*_*mhz 24
您是否在根目录中创建了配置文件: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"
]
}
Run Code Online (Sandbox Code Playgroud)
如果未创建,您可以在根目录中与 package.json 一起创建一个并粘贴上述配置。或者已经创建,您可以通过上述配置替换现有配置并重新检查。
如果按原样遵循每个步骤,CRA 文档指南就可以工作,但是当说“将任何文件重命名为 TypeScript 文件”时,它非常棘手。根据使用打字稿的源代码,您的应用程序应该包含文件。create-react-app ./tsconfig.json
如指南中所述,简单重命名仅适用于./src/index.(js|ts|jsx|tsx)文件,但只要create-react-app 配置 webpack为排除所有打字稿文件,所有导入都会失败。
我亲自检查过的 CRA 版本 5.0.1 的最小./tsconfig.json文件如下:
{
"compilerOptions": {
"esModuleInterop": true,
"jsx": "react"
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35410 次 |
| 最近记录: |