【问题标题】:Why isn't my import being found by the esm loader?为什么 esm 加载程序找不到我的导入?
【发布时间】:2021-08-04 22:14:06
【问题描述】:

我有一个小型快递服务器,并在我的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;

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

【问题讨论】:

标签: javascript typescript express node-modules


【解决方案1】:

@ASDFGerte 指出在 esm 中你必须 include the file's extension for relative imports。所以我能够通过更改来修复和运行我的代码: import app from '../app';import app from '../app.js';

【讨论】:

    猜你喜欢
    • 2018-03-26
    • 2014-04-27
    • 2014-06-26
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    相关资源
    最近更新 更多