首页 > 解决方案 > 为什么 esm 加载程序找不到我的导入?

问题描述

我有一个小型快递服务器,我在bin/www.ts我的 app.ts 文件中导入了这样的文件:

import app from '../app';

当我构建我的项目并将其转换为 JavaScript 使用:tsc --project ./ 然后运行它时,nodemon ./build/bin/www我在控制台中收到错误消息:

internal/process/esm_loader.js:74
    internalBinding('errors').triggerUncaughtException(
                              ^
Error [ERR_MODULE_NOT_FOUND]: 
Cannot find module '/Users/t86b/Desktop/Dev/Projects/TestServerProject/Server/build/app' 
imported from /Users/t86b/Desktop/Dev/Projects/TestServerProject/Server/build/bin/www.js

该文件存在于我指定的位置,我已检查并将其添加"type":"module"到我的package.json文件中。我也从 app.ts 文件中删除了所有要求,但仍然没有。我不确定此时该怎么做。这是我的package.json文件(简明扼要):

{
  ...
  "scripts": {
    "build": "tsc --project ./",
    "start": "nodemon ./build/bin/www",
    "start:dev": "nodemon -r ./bin/www.ts",
    "tsc": "tsc",
    "tsStart": "node ./build/bin/www"
  },
  ...
  "dependencies": {
    ...
    "express": "^4.17.1",
    "typescript": "^4.0.3"
  },
  "type": "module",
  "devDependencies": {
    ...
    "nodemon": "^2.0.7",
    "ts-node": "^9.1.1"
  }
}

我的ts.config

{
  "compilerOptions": {   
    "target": "es2017",
    "module": "ESNext",
    "lib": ["ES2017"],  
    "outDir": "./build",
    "rootDir": "./",
    "strict": true,
    "moduleResolution": "node", 
    "esModuleInterop": true, 
    /* Advanced Options */
    "skipLibCheck": true, 
    "forceConsistentCasingInFileNames": true   
  }
}

如果有帮助,这里是我的 app.ts,它也没有错误(为清楚起见,进行了精简):

import express from 'express';
import indexRouter from './routes/index';
...
let app = express();
app.use('/', indexRouter);

export default app;

如何让我的项目看到我的文件以便我可以启动我的服务器?提前感谢,如果您需要更多详细信息,请告诉我。

标签: javascripttypescriptexpressnode-modules

解决方案


@ASDFGerte 指出,在 esm 中,您必须包含文件的扩展名以进行相对导入。所以我能够通过更改来修复和运行我的代码 import app from '../app';import app from '../app.js';


推荐阅读