Skip to content
Advertisement

Unable to get __dirname value

I am using __dirname to get absolute path to GraphQL schema:

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

I have changed module to fit ES6 module standard and __dirname now is undefined. __dirname

How can I resolve path to schema?

Answer

There is some issue with esm + __dirname

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

Differences between ES modules and CommonJS

No __filename or __dirname

These CommonJS variables are not available in ES modules.

__filename and __dirname use cases can be replicated via import.meta.url.

try to fix by this example https://nodejs.org/api/esm.html#esm_import_meta_url

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