All Articles

Relative import paths need explicit file extensions in EcmaScript imports

Matt Pocock
Matt PocockMatt is a well-regarded TypeScript expert known for his ability to demystify complex TypeScript concepts.

The Error

Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node16' or 'nodenext'.

// Relative import paths need explicit file extensions in
// EcmaScript imports when '--moduleResolution' is 'node16'
// or 'nodenext'.

import { example } from "./foo";

The Solution That Doesn't Work

Adding a .ts extension to the import path doesn't work, and results in the following error:

An import path can only end with a '.ts' extension when 'allowImportingTsExtensions' is enabled.

// An import path can only end with a '.ts' extension when
// 'allowImportingTsExtensions' is enabled.

import { example } from "./foo.ts";

The Solution

Add the .js extension to the import path.

import { example } from "./foo.js";

Why Do We Need to Use JS File Extensions?

This error happens because you've specified moduleResolution: NodeNext. This tells TypeScript that you want your imports and exports to conform strictly to the Node spec.

The Node spec requires that you use .js file extensions for all imports and exports. This was decided so that a relative import path like ./foo.js would work both in Node and the browser.

This also simplifies Node's module resolution strategy - Node doesn't have to do any guesswork to figure out what file to import. Thanks to Gil Tayer for clarifying this for me.

What if I don't want to use JS file extensions?

  • Make sure you're using an external compiler, like esbuild, to compile your TypeScript code.
  • Change your tsconfig.json to use moduleResolution: Bundler instead of moduleResolution: NodeNext.
Matt's signature

Share this article with your friends

`any` Considered Harmful, Except For These Cases

Discover when it's appropriate to use TypeScript's any type despite its risks. Learn about legitimate cases where any is necessary.

Matt Pocock
Matt Pocock

No, TypeScript Types Don't Exist At Runtime

Learn why TypeScript's types don't exist at runtime. Discover how TypeScript compiles down to JavaScript and how it differs from other strongly-typed languages.

Matt Pocock
Matt Pocock

Deriving vs Decoupling: When NOT To Be A TypeScript Wizard

In this book teaser, we discuss deriving vs decoupling your types: when building relationships between your types or segregating them makes sense.

Matt Pocock
Matt Pocock

NoInfer: TypeScript 5.4's New Utility Type

Learn how TypeScript's new utility type, NoInfer, can improve inference behavior by controlling where types are inferred in generic functions.

Matt Pocock
Matt Pocock