为什么我的模块不在输出文件夹中?

Why isn't my module in the otuput folder?

考虑这些文件:

mymodule.mjs

export const answer = 42

tsconfig.json

{
  "compilerOptions": {
      "rootDir": "src",
      "outDir": "lib",
      "baseUrl": ".",
      "skipLibCheck": true,
      "target": "es6",
      "module": "commonjs",
      "moduleResolution": "node",
      "sourceMap": true,
      "declarationMap": true,
      "inlineSources": false,
      "declaration": true,
      "stripInternal": true,
      "lib": [
        "es2016",
        "dom"
      ],
      "strict": true,
      "noImplicitReturns": true,
      "noUnusedLocals": true
  },
  "include": [
      "src"
  ]
}

package.json:

{
  "name": "deleteme2",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "@types/jest": "^26.0.15",
    "@types/node": "^12.0.0",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "typescript": "^4.1.2",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "compile": "tsc", 
    "build": "yarn run compile",
    "start": "node lib/server.mjs",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

编译成功:

$ yarn run build

但是,当我尝试启动它时 yarn run start 我收到错误消息:

$ node lib/server.mjs
internal/modules/cjs/loader.js:892
  throw err;
  ^

Error: Cannot find module 'C:\Users\user1\Desktop\deleteme2\lib\server.mjs'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:889:15)
    at Function.Module._load (internal/modules/cjs/loader.js:745:27)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at internal/main/run_main_module.js:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}
error Command failed with exit code 1.

为什么 server.mjs 不在输出文件夹中?

因为您正在尝试使用 tsc 编译 .mjs 文件。

tsc 仅支持 .ts,.tsx 文件,因为它仅用于将 TypeScript 编译为 JavaScript。所以你不能用它来编译 .mjs,.js 或任何其他文件类型。

如果您将文件更改为 mymodule.ts 并将其放在 src/ 中(因为您只在 tsconfig.json 中包含 src),那么它应该会按预期工作.在这种情况下,输出文件将位于 .js,因此您需要改为 运行 node lib/myModule.js