Skip to content
Advertisement

Why isn’t my import being found by the esm loader?

I have a small express server and in my bin/www.ts I import my app.ts file like this:

import app from '../app';

When I build my project and turn it into JavaScript using: tsc --project ./ and then run it with nodemon ./build/bin/www I get an error in my console saying:

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

The file exists in the location I specified, I’ve checked and I’ve added the "type":"module" to my package.json file as well. I’ve removed every require from the app.ts file as well and still nothing yet. I’m not sure what to do at this point. Here is my package.json file (condensed to get to the point):

{
  ...
  "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"
  }
}

My ts.config:

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

If it helps, here is my app.ts, which also has no errors (condensed for clarity):

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

export default app;

How do I get my project to see my file so that I can start up my server? thanks in advance and let me know if you need any more details.

Advertisement

Answer

@ASDFGerte pointed out that in esm you have to include the file’s extension for relative imports. So I was able to fix and run my code by changing: import app from '../app'; to import app from '../app.js';

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement