graphql-tools icon indicating copy to clipboard operation
graphql-tools copied to clipboard

(@graphql-tools/load-files) - improve error message on import to require fallback

Open eKulshan opened this issue 3 years ago • 2 comments

Problem description. Hello! I'm rewriting my app from common js to es6 modules. So I have to move from loadFileSync to async loadFile to import my schemas and resolvers. The problem I've encountered is that if you have any troubles with your imports within resolvers, you get the error, on this line:

const defaultRequireMethod = (path) => import(path).catch(async () => require(path));
                                                                                                                  ^
ReferenceError: require is not defined
    at file:///home/jackson/work/projects/fasty/node_modules/@graphql-tools/load-files/index.mjs:155:75
    at async file:///home/jackson/work/projects/fasty/node_modules/@graphql-tools/load-files/index.mjs:162:33
    at async Promise.all (index 0)
    at async default (file:///home/jackson/work/projects/fasty/server/src/server/graphql/index.js:17:36)
    at async default (file:///home/jackson/work/projects/fasty/server/src/server/index.js:7:35)
    at async file:///home/jackson/work/projects/fasty/server/bin/index.js:10:15

Import fails due to errors in code and fallback to require. Obviously require is not defined cause I'm using es6 modules. I've spent some time figuring out what's wrong, cause error really doesn't help much to locate a problem.

The solution that helped me: Simply added console.log of error thrown by import fail and got all the problems causing that:

const defaultRequireMethod = (path: string) => import(path).catch(async (err) => {
    console.log(err)
    return require(path)
});

Request: Make import fail errors more clear and informable.

Question: Why fallback to require anyway, as using import with es6 modules will always lead to undefined require error? I'm a beginner programmer so the question is really to learn and understand. Thanks for your reply in advance.

eKulshan avatar Oct 30 '21 18:10 eKulshan

I am experiencing the same issue, and I agree with the sentiments.

pfloo avatar Nov 17 '21 21:11 pfloo

Yeah, the Fix is working and should be used

NilsDietrich avatar Dec 17 '21 01:12 NilsDietrich