首页 > 解决方案 > 无法获取 __dirname 值

问题描述

__dirname用来获取 GraphQL 模式的绝对路径:

const schema = loadSchemaSync(path.join(__dirname, './graphql/schemas/schema.graphql'), {
  loaders: [new GraphQLFileLoader()]
});

我已更改模块以适应 ES6 模块标准,__dirname现在未定义。 __目录名

如何解析模式的路径?

标签: javascriptnode.jsexpress

解决方案


esm+有一些问题__dirname

https://nodejs.org/api/esm.html#esm_no_require_exports_module_exports_filename_dirname#esm_differences_between_es_modules_and_commonjs

ES 模块和 CommonJS 的区别

没有 __filename 或 __dirname

这些 CommonJS 变量在 ES 模块中不可用。

__filename 和 __dirname 用例可以通过 import.meta.url 复制。

尝试通过此示例修复 https://nodejs.org/api/esm.html#esm_import_meta_url

loadSchemaSync(path.join(import.meta.url, './graphql/schemas/schema.graphql'), ...

推荐阅读