11

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

1 Answer 1

13

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

Sign up to request clarification or add additional context in comments.

7 Comments

This is because node.js follows the ES6 standard which forbids the interpreter from guessing filename extensions. You will also need to add file extensions if you want to use import in plain javascript in browsers. Typescript on the other hand was implemented based on the import syntax proposal before ES6 was finalized so they followed node module (commonjs) behavior which guesses file extensions. However when ES6 standard was finally published the real standard did not allow this. Node follows the real standard while typescript breaks the standard because the standard did not exist yet
Thank you for that slebetman, I've been fighting with that error all day. Now I'm just stuck being told that I can't import my files with *.ts (though they are typescript files) but have to call them *.js instead xD
@slebetman Is there a way to tell tsc to change all import to end with an extension in build time (e.g.> all arbitrary files to .js)?
@Logan It may feel weird to import .js files in a typescript program, but remember that the typescript files are translated to .js files by tsc before runtime.
Something about this seems wrong because I'm not adding .js in the browser. Is this the way libraries and other projects are doing it?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.