Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Directory import is not supported resolving ES modules' with Node.js

I'm using Node.js v14.13.0.

app.js file:

import database from './database';  database(); 

database/index.js file:

import mongoose from 'mongoose';  export default connect = async () => {     try {         await mongoose.connect('...', { });     } catch (error) {} }; 

In package.json I added "type": "module".

After running the app I get the following error:

Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import '/Users/xx/Desktop/Projects/node-starter/src/database' is not supported resolving ES modules imported from /Users/xx/Desktop/Projects/node-starter/src/app.js

like image 689
Ayoub k Avatar asked Oct 20 '20 21:10

Ayoub k


People also ask

How do I enable ES modules in node JS?

To be able to load an ES module, we need to set “type”: “module” in this file or, as an alternative, we can use the . mjs file extension as against the usual . js file extension. Also, from Node version 12.7.

Does node support ES6 import?

Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from 'express' node js will throw an error as follows: Node has experimental support for ES modules.

Where is __ Dirname defined?

The __dirname or __filename global variables are not available in ECMAScript module files. To solve the "__dirname is not defined in ES module scope" error, import and use the dirname() method from the path module. The dirname method takes a path as a parameter and returns the directory name of the path.


2 Answers

With ES6 modules you can not (yet?) import directories. Your import should look like this:

import database from "./database/index.js" 
like image 63
php_nub_qq Avatar answered Oct 17 '22 00:10

php_nub_qq


What happens here is that Node mandates using an extension in import statements and also states,

Directory indexes (e.g. './startup/index.js') must also be fully specified.

Your import database from './database'; statement doesn't specify the index.js. You can add index.js as suggested in another answer, but that approach doesn't look elegant in TypeScript projects, when you'd end up importing a .js file from a .ts one.

You can change this Node extension resolution behavior by passing the --experimental-specifier-resolution=node flag. This will work and will keep your code unchanged:

app.js

import database from './database'; database(); 

Run as: node --experimental-specifier-resolution=node app.js.

A Node developer admitted that the documentation wasn't that clear.

like image 25
Dan Dascalescu Avatar answered Oct 16 '22 23:10

Dan Dascalescu