TypeScript "Cannot find module" 에러

한호수 (The Lake)·2022년 11월 15일
0
post-thumbnail

React에서 TypeScript를 사용해보려고 하는데 처음부터 실행이 되지 않고 에러가 무더기로 발생했다.

문제

일단 React 에서 TypeScript를 추가할때 아래와 같이 두가지 방법(yarn 제외)을 권장하지만 난 두번째 방법으로 설치하였다.

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

혹은

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

설치 후 .jsx 확장자들을 모두 .tsx 로 변경하였다.

그리고 실행했더니

Compiled with problems:X

ERROR in src/App.tsx:6:10

TS17004: Cannot use JSX unless the '--jsx' flag is provided.
    4 |
    5 | function App() {
  > 6 |   return <Container>hi</Container>;
      |          ^^^^^^^^^^^
    7 | }
    8 |
    9 | export default App;


ERROR in src/index.tsx:1:8

TS1192: Module '"/mnt/d/Workspace/ReactMatserClass/class1/node_modules/@types/react-dom/index"' has no default export.
  > 1 | import ReactDOM from "react-dom";
      |        ^^^^^^^^
    2 | import App from "./App";
    3 |
    4 | ReactDOM.render(<App />, document.getElementById("root"));


ERROR in src/index.tsx:2:17

TS6142: Module './App' was resolved to '/mnt/d/Workspace/ReactMatserClass/class1/src/App.tsx', but '--jsx' is not set.
    1 | import ReactDOM from "react-dom";
  > 2 | import App from "./App";
      |                 ^^^^^^^
    3 |
    4 | ReactDOM.render(<App />, document.getElementById("root"));
    5 |


ERROR in src/index.tsx:4:17

TS17004: Cannot use JSX unless the '--jsx' flag is provided.
    2 | import App from "./App";
    3 |
  > 4 | ReactDOM.render(<App />, document.getElementById("root"));
      |                 ^^^^^^^
    5 |
    

무수한 에러가 발생하였다.

해결방법

  1. npm install로 직접 설치해서 그런지 package.json 파일과 같은 경로에 tsconfig.json 파일이 없었다. 직접 만들어주자.
  2. TS17004: Cannot use JSX unless the '--jsx' flag is provided.
{ 
  "compilerOptions": {
    "jsx": "react-jsx"
  }
}

tsconfig.json 파일에 직접 적어서 추가해주자.

  1. 대부분의 에러가 사라졌지만 한가지 에러가 더 남아있다.
Compiled with problems:X

ERROR in src/index.tsx:1:8

TS1192: Module '"/mnt/d/Workspace/ReactMatserClass/class1/node_modules/@types/react-dom/index"' has no default export.
  > 1 | import ReactDOM from "react-dom";
      |        ^^^^^^^^
    2 | import App from "./App";
    3 |
    4 | ReactDOM.render(<App />, document.getElementById("root"));
  1. tsconfig.json 파일에 한 줄 더 추가해주자.
    {
     "compilerOptions": {
       "allowSyntheticDefaultImports": true, // 이 부분
       "jsx": "react-jsx"
     }
    }
  2. 잘 작동하는것을 볼 수 있었다.
profile
항상 근거를 찾는 사람이 되자

0개의 댓글