Skip to content

Commit

Permalink
Fix: ESM parse errors should be catch-able (#29)
Browse files Browse the repository at this point in the history
* fix: map import errors to promise rejection

* test: parse errors are catch-able

* chore: changeset
  • Loading branch information
bholmesdev authored Sep 1, 2022
1 parent b13bed6 commit 0133f2a
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/cyan-dingos-fly.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@proload/core": patch
---

Fix: make ESM parse errors catch-able
1 change: 1 addition & 0 deletions fixtures/esm-parse-error/test.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export defau
9 changes: 7 additions & 2 deletions packages/core/lib/esm/requireOrImport.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,19 @@ let require = createRequire(import.meta.url);
export default async function requireOrImport(filePath, { middleware = [] } = {}) {
await Promise.all(middleware.map(plugin => plugin.register(filePath)));

return new Promise((resolve, reject) => {
return new Promise(async (resolve, reject) => {
try {
let mdl = require(filePath);
resolve(mdl);
} catch (e) {
if (e.code === 'ERR_REQUIRE_ESM') {
const fileUrl = pathToFileURL(filePath).toString();
return import(fileUrl).then(mdl => resolve(mdl));
try {
const mdl = await import(fileUrl);
return resolve(mdl);
} catch (e) {
reject(e);
}
};
reject(e);
}
Expand Down
10 changes: 10 additions & 0 deletions packages/core/test/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ test('exact filePath', async () => {
is(mdl.value.value, 'exact-filePath')
});

test('ESM parse errors should be catch-able', async () => {
let err = 0;
try {
await load('test', { cwd: resolve(`fixtures/esm-parse-error`) });
} catch (e) {
err += 1;
}
is(err, 1);
});

test('missing but mustExist (default)', async () => {
let err = 0;
try {
Expand Down

0 comments on commit 0133f2a

Please sign in to comment.