Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(esm): add support for .gmrc as an ES Module #140

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions src/commands/_common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,36 @@ interface Options {
*/
export async function getSettings(options: Options = {}): Promise<Settings> {
const { configFile } = options;
const tryRequire = (path: string): Settings => {
const tryImport = async (
path: string,
mode: "cjs" | "mjs" | "js",
): Promise<Settings> => {
// If the file is e.g. `foo.js` then Node `require('foo.js')` would look in
// `node_modules`; we don't want this - instead force it to be a relative
// path.
const relativePath = resolve(process.cwd(), path);

try {
return require(relativePath);
if (mode === "cjs") {
return require(relativePath);
} else if (mode === "mjs") {
return (await import(relativePath)).default;
} else {
// try and require(CJS); but on ESM error, retry with import
try {
return require(relativePath);
} catch (e) {
if (
e.code === "ERR_REQUIRE_ESM" ||
(e.constructor.name === "SyntaxError" &&
e.message.includes(" token 'export'"))
) {
return tryImport(relativePath, "mjs");
} else {
throw e;
}
}
}
} catch (e) {
throw new Error(
`Failed to import '${relativePath}'; error:\n ${e.stack.replace(
Expand All @@ -87,14 +109,18 @@ export async function getSettings(options: Options = {}): Promise<Settings> {
}

if (configFile.endsWith(".js")) {
return tryRequire(configFile);
return tryImport(configFile, "js");
} else if (configFile.endsWith(".mjs")) {
return tryImport(configFile, "mjs");
} else if (configFile.endsWith(".cjs")) {
return tryImport(configFile, "cjs");
} else {
return await getSettingsFromJSON(configFile);
}
} else if (await exists(DEFAULT_GMRC_PATH)) {
return await getSettingsFromJSON(DEFAULT_GMRC_PATH);
} else if (await exists(DEFAULT_GMRCJS_PATH)) {
return tryRequire(DEFAULT_GMRCJS_PATH);
return tryImport(DEFAULT_GMRCJS_PATH, "js");
} else {
throw new Error(
"No .gmrc file found; please run `graphile-migrate init` first.",
Expand Down