从节点手册中我看到我可以获取文件的目录__dirname,但是从REPL看来这似乎是未定义的.这是我的误解还是错误在哪里?
$ node
> console.log(__dirname)
ReferenceError: __dirname is not defined
at repl:1:14
at REPLServer.eval (repl.js:80:21)
at Interface.<anonymous> (repl.js:182:12)
at Interface.emit (events.js:67:17)
at Interface._onLine (readline.js:162:10)
at Interface._line (readline.js:426:8)
at Interface._ttyWrite (readline.js:603:14)
at ReadStream.<anonymous> (readline.js:82:12)
at ReadStream.emit (events.js:88:20)
at ReadStream._emitKey (tty.js:320:10)
Run Code Online (Sandbox Code Playgroud) 我--experimental-modules在运行节点应用程序时使用该标志以使用ES6模块.
但是,当我使用此标志时,元变量__dirname不可用.是否有另一种方法可以获得__dirname与此模式兼容的相同字符串?
我最近在我的 NodeJS 项目中从 CommonJS 切换到了 ES6 模块。我面临的挑战之一是在导入模块之一之前定义一个全局变量。我曾经在我的主文件中使用 CommonJS 来做到这一点:
const path = require('path');
global.appRoot = path.resolve(__dirname);
const myObj = require('./my-object-file');
Run Code Online (Sandbox Code Playgroud)
我my-object-file用的地方global.appRoot。
对于 ES6,我尝试过以下操作:
import path from 'path';
global.appRoot = path.resolve(path.resolve());
import myObj from './my-object-file';
Run Code Online (Sandbox Code Playgroud)
与my-object-file.js是:
export default {
root: global.appRoot
}
Run Code Online (Sandbox Code Playgroud)
global.appRoot但我的in未定义my-object-file.js。
这里发生了什么?
导入模块是否在我的代码中的任何内容之前被调用?
我该如何解决这个问题(知道我绝对希望能够将路径定义为可在模块中访问的全局变量)?