Search code examples
reactjstypescriptjsxcreate-react-apptsx

tsc compile in React (create-react-app) needs explicit compile flags altough I set them in tsconfig.json


I first initialized a react app with "create-react-app" and afterwards added typescript to it with yarn add typescript @types/node @types/react @types/react-dom @types/jest I initialized tsconfig.json with defaults:

{
  "compilerOptions": {
    "target": "es5",
    "module": "esnext",
    "allowJs": true,
    "jsx": "react-jsx",
    "sourceMap": true,
    "outDir": "./dist",
    "noEmit": true,
    "isolatedModules": true,
    "strict": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "noFallthroughCasesInSwitch": true,
    "resolveJsonModule": true
  },
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ],
  "include": [
    "./src/**/*.tsx"
  ]
}

If I try to compile single files like tsc App.tsx I get errors saying I need to use --jsx flag and --esModuleInterop flag. But I have set them in tsconfig.json already, why do I have to explicitely specify them in command line? It only works so: tsc index.tsx --jsx preserve --esModuleInterOp But why?


Solution

  • From docs:

    tsc index.ts

    emits JS for just the index.ts with the compiler defaults (not the project's tsconfig)

    And, you can't specify file/s to compile and the tsconfig file on the CLI:

    tsc index.ts tsconfig.json // NOT ALLOWED
    

    So, if you are using CLI to compile just one or more files, you must provide the options (jsx and esModuleInterOp in this case) or create new tsconfig file that extends the existing one, and add your file to it.