Node.js 中的错误 [ERR_UNSUPPORTED_DIR_IMPORT]

Node.js 中的错误[ERR_UNSUPPORTED_DIR_IMPORT]

Error [ERR_UNSUPPORTED_DIR_IMPORT] in Node.js

当我们尝试使用目录导入时,Node.js 中出现“错误[ERR_UNSUPPORTED_DIR_IMPORT] :不支持目录导入”。要解决该错误,请在导入中明确指定index.js文件名或使用
--experimental-specifier-resolution标志。

错误错误不支持的目录导入

下面是错误如何发生的示例。这是一个名为index.js.

索引.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; }

这是一个consumer-file.jsindex.js.

消费者.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);

文件中隐式导入语句的问题consumer.js是默认情况下 Node.js 要求您
显式指定模块的完整路径

解决该错误的最佳方法是在导入语句中明确提供完整路径。

消费者.js
// ✅ 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"
Node.js 在解析 ES 模块时不支持目录导入,所以我们必须显式指定完整路径。

话虽如此,您可以使用一个实验标志来启用从包含索引文件的目录导入。标志是
–experimental-specifier-resolution=node

node --experimental-specifier-resolution=node consumer-file.js

因此,如果我将导入恢复consumer.js为目录导入:

消费者.js
import multiply, {increaseSalary, department} from './'; console.log(multiply(10, 10)); // 👉️ 100 console.log(increaseSalary(100)); // 👉️ 200 console.log(department); // 👉️ "accounting"

现在我可以--experimental-specifier-resolution在发出节点命令时使用该标志来启用从包含索引文件的目录中导入。

node --experimental-specifier-resolution=node consumer-file.js

实验说明符分辨率

The Node.js documentation explicitly states that we shouldn’t rely on this flag because they plan to remove it.

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.

Conclusion #

当我们尝试使用目录导入时,Node.js 中出现“错误[ERR_UNSUPPORTED_DIR_IMPORT] :不支持目录导入”。要解决该错误,请在导入中明确指定index.js文件名或使用
--experimental-specifier-resolution标志。