[英]Module not found: Error: Can't resolve the typescript file when adding typescript to a CRA app
I'm trying to add typescript
to my project and write new components with typescript.我正在尝试将
typescript
添加到我的项目中并使用打字稿编写新组件。 I followed the documentation but I'm got this error:我按照文档进行操作,但出现此错误:
can't resolve [the typescript file]
this happens even with a fresh create-react-app
project.即使是新的
create-react-app
项目也会发生这种情况。
according to CRA documentation for adding typescript
To an existing Create React App project, first, we must install typescript
and type definition files
:根据CRA documentation for adding
typescript
To an existing Create React App project,首先,我们必须安装typescript
和type definition files
:
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
almost done!快完成了!
rename a js/jsx
file to tsx
and restart your development server!将
js/jsx
文件重命名为tsx
并重新启动您的开发服务器!
for simplicity, I'm creating a typescript
file named test.tsx
that contains the Test
component:为简单起见,我正在创建一个名为
test.tsx
的typescript
文件,其中包含Test
组件:
export default function Test(){
return (
<div>this is test to see typescirpt</div>
)
}
and importing it to the main.js
and rendering it:并将其导入
main.js
并渲染它:
import Test from "./test";
function App() {
return (
<div className="App">
<Test />
</div>
);
}
export default App;
now I'm restarting the development server (I closed the previous one with CRTL+c
) with npm start
.现在我正在使用
npm start
重新启动开发服务器(我用CRTL+c
关闭了前一个)。
I got this error:我收到此错误:
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'
I used a fresh create-react-app
project, followed the documentation, and saw this error.我使用了一个新的
create-react-app
项目,按照文档操作,看到了这个错误。 (why?) (为什么?)
this is my installed dependencies:这是我安装的依赖项:
"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"
},
Have you created a config file: tsconfig.json in your root directory?您是否在根目录中创建了配置文件:tsconfig.json? I didn't see this being mentioned in the question.
我没有看到问题中提到了这一点。
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"
]
}
If not created, you can create one in root directory alongside package.json and paste the above configs.如果未创建,您可以在 package.json 旁边的根目录中创建一个并粘贴上述配置。 OR else already created, you can replace the existing config by above config and recheck.
或者已经创建,您可以通过上述配置替换现有配置并重新检查。
CRA Documentation guide works if follow each step as is but it's very tricky when saying "rename any file to be a TypeScript file".如果按照原样执行每个步骤, CRA 文档指南将起作用,但在说“将任何文件重命名为 TypeScript 文件”时非常棘手。 According to source code of
create-react-app
to use typescript your app should contain ./tsconfig.json
file.根据
create-react-app
源代码使用 typescript 您的应用程序应包含./tsconfig.json
文件。
Simple renaming, as described in guide, works only for ./src/index.(js|ts|jsx|tsx)
file but all imports will fail as far as create-react-app
configurates webpack
to exclude all typescript files.如指南中所述,简单重命名仅适用于
./src/index.(js|ts|jsx|tsx)
文件,但只要create-react-app
配置webpack
以排除所有 typescript 文件,所有导入都将失败。
Minimal ./tsconfig.json
file, as I personally checked for CRA version 5.0.1 is a following one:最小
./tsconfig.json
文件,因为我亲自检查了 CRA 版本 5.0.1 是以下一个:
{
"compilerOptions": {
"esModuleInterop": true,
"jsx": "react"
}
}
After 3 days of insanity, what worked for me was updating the tsconfig.json
file by adding the rootDir
and outDir
property like this:经过 3 天的疯狂之后,对我有用的是通过添加
rootDir
和outDir
属性来更新tsconfig.json
文件,如下所示:
"compilerOptions": {
//...
"outDir": "../../dist",
"rootDir": "."
},
Then delete all dist
inside the project.然后删除项目内的所有
dist
。 After that I ran npm run build
and it worked.之后,我运行
npm run build
并且它工作。 Hope it helps someone else.希望它可以帮助别人。
Despite what the docs suggest it seems when migrating from JS to TS you do actually need to provide a tsconfig.json
file.尽管文档建议在从 JS 迁移到 TS 时看起来确实需要提供一个
tsconfig.json
文件。
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext", "webworker"],
"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"]
}
I also searched a lot and finally I found the useful way for myself:我也搜索了很多,最后我找到了对自己有用的方法:
I added tsconfig.json file in the root and added these codes to it:我在根目录中添加了 tsconfig.json 文件并将这些代码添加到其中:
I got help form this site to solve it我得到了这个网站的帮助来解决它
the entire code of my tsconfig.json was this:我的 tsconfig.json 的整个代码是这样的:
{ "compilerOptions": { "baseUrl": ".", "paths": { "*": [ "*", "components/*" ] }, "allowJs": false, "allowSyntheticDefaultImports": true, "allowUnreachableCode": false, "allowUnusedLabels": false, "alwaysStrict": true, "charset": "utf8", "checkJs": false, "declaration": true, "disableSizeLimit": false, "downlevelIteration": false, "emitBOM": false, "emitDecoratorMetadata": true, "esModuleInterop": true, "experimentalDecorators": true, "forceConsistentCasingInFileNames": true, "importHelpers": false, "inlineSourceMap": false, "inlineSources": false, "isolatedModules": false, "lib": [ "es2017", "esnext.asynciterable" ], "locale": "en-us", "module": "commonjs", "moduleResolution": "node", "newLine": "lf", "noEmit": false, "noEmitHelpers": false, "noEmitOnError": true, "noErrorTruncation": true, "noFallthroughCasesInSwitch": true, "noImplicitAny": true, "noImplicitReturns": true, "noImplicitThis": true, "noStrictGenericChecks": false, "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitUseStrict": false, "noLib": false, "noResolve": false, "preserveConstEnums": true, "removeComments": false, "skipLibCheck": true, "sourceMap": true, "strict": true, "strictNullChecks": true, "suppressExcessPropertyErrors": false, "suppressImplicitAnyIndexErrors": false, "target": "es2017", "traceResolution": false, "rootDir": "", "outDir": "../../build/lib", "typeRoots": [] }, "include": [ "**/*.ts" ], "exclude": [] }
Just had this issue myself.我自己就有这个问题。 For me, webpack was not resolving typescript files.
对我来说,webpack 没有解析 typescript 文件。
If you're using webpack - add the following to your webpack.config.js如果您使用的是 webpack - 将以下内容添加到您的 webpack.config.js
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
},
As bnays mhz said you have to create a tsconfig.json
in root and add that same content he provided, also you have to rename all .js
files to .tsx
and it will compile your application with Type errors which you have to resolve manually.正如bnays mhz所说,您必须在根目录中创建一个
tsconfig.json
并添加他提供的相同内容,您还必须将所有.js
文件重命名为.tsx
,它会编译您的应用程序,其中包含您必须手动解决的类型错误。
But instead of doing this, I suggest you use the typescript
template.但我建议您不要这样做,而是使用
typescript
模板。
npx create-react-app my-app --template typescript
It will configure everything for you, and you can start with ease.它将为您配置一切,您可以轻松开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.