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

Posted

技术标签:

【中文标题】为啥我的模块不在输出文件夹中?【英文标题】:Why isn't my module in the otuput folder?为什么我的模块不在输出文件夹中? 【发布时间】:2021-11-12 16:18:45 【问题描述】:

考虑这些文件:

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

【问题讨论】:

【参考方案1】:

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

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

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

【讨论】:

这么简单,不敢相信我错过了:)

以上是关于为啥我的模块不在输出文件夹中?的主要内容,如果未能解决你的问题,请参考以下文章

为啥我的脚本目录不在 Python sys.path 中?

为啥 awesome_print 不在我的 Rails 4.2 控制台中打印出格式化输出?

为啥 Asp.Net MVC 不在我的共享目录中搜索视图?

为啥不在 Vue 和 Vue Router 生产环境中渲染我的组件?

为啥 maven 不在我的 jar 中包含 JSP 文件?

为啥 require('fs') 导致我的 js 变量不在 html 中显示?