machineghost
machineghost

Reputation: 35730

Is it possible to make Node NOT Require the ".js" Extension For Imports?

Node now has built-in support for imports, which is awesome. But that support requires you to specify the file extension, which is annoying.

I'm sure there's some justification for why this is (likely having to do with their weird obsession with the .mjs extension), but is there any way to work around it and make import work "like normal" (where you can leave .js off)?

Upvotes: 9

Views: 7130

Answers (2)

machineghost
machineghost

Reputation: 35730

I fixed this was with the esm package.

In short, the Node organization has done an awful job of rolling out ES Module support, but the saving grace is that in the meantime the guy who made the Lodash library has already added far better support, and it's super easy to get.

Two steps:

  1. npm i esm
  2. node -r esm index.js (instead of just node index.js)

If you just do the above you don't need any special Node flags (like experimental-modules) or anything else, and ES Module syntax (import/export) will work perfectly in your application ... including not requiring .js in imports.

Upvotes: 3

dobryy
dobryy

Reputation: 116

You can achieve this by setting "type": "module" on a top level of your package.json and running nodejs with --experimental-specifier-resolution=node command line switch (works for nodejs v14)

Upvotes: 8

Related Questions