简体   繁体   中英

Why a TypeScript project generated with Create React App can find modules and an Express one doesn't?

I use WebStorm, I created a React project and an Express project with a build-in wizard. I manually added TypeScript to the latter. Here's my tsconfig.json for React:

{
  "compilerOptions": {
    "target": "es2017",
    "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"
  ]
}

And here's one for express:

{
  "compilerOptions": {
    "sourceMap": true,
    "outDir": "output",
    "esModuleInterop": true,
    "noImplicitAny": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "strict": true,
    "isolatedModules": true,
    "module": "esnext",
    "target": "es2017",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "allowJS" : true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "source/**/*"
  ]
}

For the express project I needed to set "type": "module" in package.json .

The problem: when I use import in the React project I don't need to add the extension .js to file names, but in the Express project it's necessary, otherwise I'm getting ERR_MODULE_NOT_FOUND .

import {serviceRouter} from "./ServiceRouter";

vs

import {serviceRouter} from "./ServiceRouter.js";

When using ES6 modules ( "type": "module" ), extensions are mandatory, see https://nodejs.org/api/esm.html#esm_mandatory_file_extensions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM