16

I'm trying to add typescript to my project and write new components with 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.
according to CRA documentation for adding typescript To an existing Create React App project, first, we must install typescript and 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!

for simplicity, I'm creating a typescript file named test.tsx that contains the Test component:

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

and importing it to the main.js and rendering it:

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.
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. (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"
  },
Gaetan C.
  • 1,742
  • 13
  • 21
kankan256
  • 210
  • 1
  • 4
  • 18
  • "Webpack does not look for .ts files by default.": https://stackoverflow.com/questions/43595555/webpack-cant-resolve-typescript-modules – Mohammad Tbeishat Apr 15 '22 at 14:17
  • documentation I mentioned says: just to these two steps (installing requirements and restarting the development server) – kankan256 Apr 15 '22 at 14:21
  • Try: import Test from "./test.tsx" – Mohammad Tbeishat Apr 15 '22 at 14:26
  • this is a wired suggestion that you make, CRA says do these to achieve `typescript` and a tsconfig file. so now how do I create the tsconfig file? with `tsc --init`. are these works safe to do? why not simply follow the documentation?? – kankan256 Apr 15 '22 at 14:36
  • 1
    Guess, you already did follow the documentation! Then, it's normal to start by narrowing up the problem..! I didn't write an answer but a comment :v – Mohammad Tbeishat Apr 15 '22 at 15:12

8 Answers8

21

Have you created a config file: tsconfig.json in your root directory? I didn't see this being mentioned in the question.

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. OR else already created, you can replace the existing config by above config and recheck.

bnays mhz
  • 425
  • 2
  • 7
  • 1
    [in this part of documentation](https://create-react-app.dev/docs/adding-typescript/#getting-started-with-typescript-and-react) said it will be created automatically. – kankan256 Apr 21 '22 at 09:58
  • also, I downgraded to CRA 4.0.3 and it created automatically. beside this look at [this part of source code](https://github.com/facebook/create-react-app/blob/f99167c014a728ec856bda14f87181d90b050813/packages/react-scripts/scripts/utils/verifyTypeScriptSetup.js#L41) it checks the existence of .ts files and creates tsconfig file. – kankan256 Apr 21 '22 at 10:02
  • maybe I must create a new fresh CRA app with "typescript" template and copy my files there. – kankan256 Apr 21 '22 at 10:03
5

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". According to source code of create-react-app to use typescript your app should contain ./tsconfig.json file.

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.

Minimal ./tsconfig.json file, as I personally checked for CRA version 5.0.1 is a following one:

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

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

I got help form this site to solve it

the entire code of my tsconfig.json was this:

{
    "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": []
}
Diana
  • 36
  • 3
1

Just had this issue myself. For me, webpack was not resolving typescript files.

If you're using webpack - add the following to your webpack.config.js

resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
},
jcdiprose
  • 41
  • 3
0

After 3 days of insanity, what worked for me was updating the tsconfig.json file by adding the rootDir and outDir property like this:

  "compilerOptions": {
    //...
    "outDir": "../../dist",
    "rootDir": "."
  },

Then delete all dist inside the project. After that I ran npm run build and it worked. Hope it helps someone else.

Einer
  • 505
  • 1
  • 6
  • 15
0

Despite what the docs suggest it seems when migrating from JS to TS you do actually need to provide a tsconfig.json file.

{
  "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"]
}
Tim
  • 4,471
  • 5
  • 36
  • 42
0
{
  "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"]
}
bright
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 25 '23 at 17:39
-1

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.

But instead of doing this, I suggest you use the typescript template.

npx create-react-app my-app --template typescript

It will configure everything for you, and you can start with ease.

ShuLaPy
  • 151
  • 7