Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node requires file extension for import statement

I've been building a typescript app, in which I imported some constants from a file. VS Code's Auto-Import did the work for me, but when I compiled and ran the file, it threw an error because it couldn't find the module. It seems that the error comes from not having file extensions for the import statements, but it only appears in the compiled javascript and not in the typescript files.

index.ts:

import { __port__ } from "./constants";
import express from "express";
const app = express();
app.listen(__port__, () => console.log("listening on port" + __port__));

constants.ts:

export const __port__ = process.env.PORT || 3000;

node.js error message:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/af2111/Desktop/Coding/myapp/server/dist/constants' imported from /home/af2111/Desktop/Coding/myapp/server/dist/index.js
like image 271
af2111 Avatar asked Mar 31 '26 19:03

af2111


1 Answers

I fixed it, I had to add a .js extension in the import statements

like image 181
af2111 Avatar answered Apr 03 '26 09:04

af2111



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!