Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do we need to add file extension when importing JavaScript modules?

When importing modules, I noticed sometimes imported files have their extension, example:

import { myFunc } from './foo.js';

Whereas other libraries, the imports do not:

import { myFunc } from './foo';

Is this related to ES modules vs CommonJS modules?

like image 338
sal3jfc Avatar asked Aug 31 '25 15:08

sal3jfc


1 Answers

It depends on your runtime and compilation environment, and also on whether you are using ES modules (the import syntax) or CommonJS modules (the require syntax). Find below an overview of the most common cases:

  • Webpack (used by Create React App and others tools) works with ES modules like so:

If the path has a file extension, then the file is bundled straightaway. Otherwise, the file extension is resolved using the resolve.extensions option, which tells the resolver which extensions are acceptable for resolution, e.g. .js, .jsx. More on the official doc.

  • If you are using ES modules with Node.js or in the browser without any compilation step:

A file extension must be provided when using the import keyword to resolve relative or absolute specifiers... This behavior matches how import behaves in browser environments... More on the official doc.

  • If you are using CommonJS modules with Node.js:

If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions: .js, .json, and finally .node. More on the official doc.

like image 121
yousoumar Avatar answered Sep 02 '25 12:09

yousoumar