簡體   English   中英

為什么使用 Create React App 生成的 TypeScript 項目可以找到模塊,而 Express 則不能?

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

我使用 WebStorm,我創建了一個 React 項目和一個帶有內置向導的 Express 項目。 我手動將 TypeScript 添加到后者。 這是我的tsconfig.json用於 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"
  ]
}

這是一個快遞:

{
  "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/**/*"
  ]
}

對於快遞項目,我需要在package.json中設置"type": "module"

問題:當我在 React 項目中使用import時,我不需要將擴展名.js添加到文件名中,但在 Express 項目中這是必需的,否則我會得到ERR_MODULE_NOT_FOUND

import {serviceRouter} from "./ServiceRouter";

對比

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

使用 ES6 模塊時( "type": "module" ),擴展是強制性的,見https://nodejs.org/api/esm.html#esm_mandatory_file_extensions

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM