af2111
af2111

Reputation: 329

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

Upvotes: 11

Views: 13024

Answers (1)

af2111
af2111

Reputation: 329

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

Upvotes: 13

Related Questions