Skip to content

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

@eKulshan

Description

@eKulshan

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions