简体   繁体   English

__dirname 没有定义在 Node.js 10 实验?

[英]__dirname is not defined in Node.js 10 experimental?

I am using Node.js 10.0.0 & my index.mjs looks like:我正在使用 Node.js 10.0.0 & 我的index.mjs看起来像:

import path from "path";

console.log(__dirname);

In my terminal, I run在我的终端,我运行

node --experimental-modules index.mjs

And I get the following error:我收到以下错误:

(node:3750) ExperimentalWarning: The ESM module loader is experimental.
ReferenceError: __dirname is not defined
at file:///MyFolderPath/node-10/index.mjs:3:21
at ModuleJob.run (internal/modules/esm/module_job.js:106:14)

ESM is not node-specific, and node-specific "globals" (such as __dirname and module) will not work. ESM 不是特定于节点的,并且特定于节点的“全局变量”(例如__dirname和模块)将不起作用。 import.meta is expected to provide a suitable replacement. import.meta有望提供合适的替代品。

Source: GitHub issue .来源:GitHub问题

ES6 modules don't define __dirname . ES6 模块不定义__dirname You can define it yourself using code like this below.您可以使用如下代码自行定义它。 This assumes a filesystem context, not a browser.这假定文件系统上下文,而不是浏览器。

import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);

See import.meta in the node reference and MDN for specifics.有关详细信息,请参阅节点参考MDN中的import.meta

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM