Last updated: Apr 5, 2024
Reading timeยท2 min
The "Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import is not supported" occurs in Node.js, when we try to use a directory import.
To solve the error, explicitly specify the index.js
filename in the import
or use the --experimental-specifier-resolution
flag.
Here is an example of how the error occurs. This is a file called index.js
.
// ๐๏ธ named export export function increaseSalary(salary) { return salary + 100; } // ๐๏ธ named export export const department = 'accounting'; // ๐๏ธ default export export default function multiply(a, b) { return a * b; }
And here is a file called consumer-file.js
that imports from index.js
.
// โ๏ธ Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import // '/bobbyhadz-js/' is not supported resolving ES modules // imported from /bobbyhadz-js/consumer-file.js // Did you mean to import ../index.js? import multiply, {increaseSalary, department} from './'; console.log(multiply(10, 10)); console.log(increaseSalary(100)); console.log(department);
The problem with the implicit import statement in the consumer.js
file is that
by default, Node.js requires you to
explicitly specify the full path
to a module.
The best way to solve the error is to explicitly provide the full path in your import statement.
// โ works as intended with full path import multiply, {increaseSalary, department} from './index.js'; console.log(multiply(10, 10)); // ๐๏ธ 100 console.log(increaseSalary(100)); // ๐๏ธ 200 console.log(department); // ๐๏ธ "accounting"
Having said that, there is an experimental flag you can use to enable importing from directories that contain an index file. The flag is --experimental-specifier-resolution=node.
node --experimental-specifier-resolution=node consumer-file.js
So, if I revert my import in consumer.js
to a directory import:
import multiply, {increaseSalary, department} from './'; console.log(multiply(10, 10)); // ๐๏ธ 100 console.log(increaseSalary(100)); // ๐๏ธ 200 console.log(department); // ๐๏ธ "accounting"
Now I can use the --experimental-specifier-resolution
flag when issuing the
node command to enable importing from directories that contain an index file.
node --experimental-specifier-resolution=node consumer-file.js
There is always a risk when relying on experimental flags, because if you update your Node.js version, the flag might not exist anymore.
My approach would be to explicitly specify the full path to the file, rather than rely on the experimental flag because these things are hard to keep track of.
One day, I might update my server's Node.js version and have my application break in production because the experimental flag has been removed.