Skip to content

Commit 525e391

Browse files
committedDec 17, 2021
fix(load-files): use createRequire in case of ESM
1 parent e6e9f91 commit 525e391

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed
 

‎.changeset/famous-students-compete.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@graphql-tools/load-files': patch
3+
---
4+
5+
fix(load-files): use createRequire in case of ESM

‎packages/load-files/src/index.ts

+14-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import globby, { sync as globbySync, GlobbyOptions } from 'globby';
22
import unixify from 'unixify';
3-
import { extname } from 'path';
3+
import { extname, join } from 'path';
44
import { statSync, readFileSync, promises as fsPromises } from 'fs';
55
import { DocumentNode, parse } from 'graphql';
6+
import { createRequire } from 'module';
7+
import { cwd } from 'process';
68

79
const { readFile, stat } = fsPromises;
810

@@ -113,6 +115,7 @@ const LoadFilesDefaultOptions: LoadFilesOptions = {
113115
requireMethod: null,
114116
globOptions: {
115117
absolute: true,
118+
cwd: cwd(),
116119
},
117120
exportNames: DEFAULT_EXPORT_NAMES,
118121
recursive: true,
@@ -139,7 +142,7 @@ export function loadFilesSync<T = any>(
139142
);
140143

141144
const extractExports = execOptions.extractExports || DEFAULT_EXTRACT_EXPORTS_FACTORY(execOptions.exportNames ?? []);
142-
const requireMethod = execOptions.requireMethod || require;
145+
const requireMethod = execOptions.requireMethod || createRequire(join(options?.globOptions?.cwd || cwd(), 'noop.js'));
143146

144147
return relevantPaths
145148
.map(path => {
@@ -225,7 +228,15 @@ export async function loadFiles(
225228
);
226229

227230
const extractExports = execOptions.extractExports || DEFAULT_EXTRACT_EXPORTS_FACTORY(execOptions.exportNames ?? []);
228-
const defaultRequireMethod = (path: string) => import(path).catch(async () => require(path));
231+
const defaultRequireMethod = (path: string) =>
232+
import(path).catch(importError => {
233+
const cwdRequire = createRequire(join(options?.globOptions?.cwd || cwd(), 'noop.js'));
234+
try {
235+
return cwdRequire(path);
236+
} catch (e) {
237+
throw importError;
238+
}
239+
});
229240
const requireMethod = execOptions.requireMethod || defaultRequireMethod;
230241

231242
return Promise.all(

1 commit comments

Comments
 (1)
Please sign in to comment.