I’ve heard that when importing ES modules, you’re supposed to include a file extension. However, I came across some Node projects that import ES modules without an extension, like in this example.
I’m wondering how they do that.
I’ve heard that when importing ES modules, you’re supposed to include a file extension. However, I came across some Node projects that import ES modules without an extension, like in this example.
I’m wondering how they do that.
2
Answers
That’s right, with ES you must include the extension. However, when you work with Typescript, it automatically recognizes the extension, and if you put it, it gives an error, unless you activate the feature ‘allowImportingTsExtensions’. Example:
I would say it depends on how it is set up in the company where you work.
Regarding your statement
Yes, this is covered in the documentation for NodeJS ESM, under import-specifiers:
and under the Mandatory File Extensions section:
As for your next statement,
The example you linked is for a TypeScript project, not a regular ESM JavaScript/NodeJS project.
Looking at lines 4 and 5 of the project’s tsconfig.json, we can see that there is
A good place to start is TypeScript’s documentation on Module Resolution. which explains how the extensions can be omitted.
For example, under the description for "node10" (which aliases to node for backwards compatibility), the following is stated:
and again in the Module – References: Extensionless Relative Paths section, we see that:
Hope this helps :).