Skip to content

Commit

Permalink
Add file location when SyntaxError happens in ESM (#4557)
Browse files Browse the repository at this point in the history
  • Loading branch information
giltayar authored Feb 3, 2021
1 parent 84d0c96 commit 9878f32
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
24 changes: 23 additions & 1 deletion lib/esm-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,29 @@ const url = require('url');

const formattedImport = async file => {
if (path.isAbsolute(file)) {
return import(url.pathToFileURL(file));
try {
return await import(url.pathToFileURL(file));
} catch (err) {
// This is a hack created because ESM in Node.js (at least in Node v15.5.1) does not emit
// the location of the syntax error in the error thrown.
// This is problematic because the user can't see what file has the problem,
// so we add the file location to the error.
// This `if` should be removed once Node.js fixes the problem.
if (
err instanceof SyntaxError &&
err.message &&
err.stack &&
!err.stack.includes(file)
) {
const newErrorWithFilename = new SyntaxError(err.message);
newErrorWithFilename.stack = err.stack.replace(
/^SyntaxError/,
`SyntaxError[ @${file} ]`
);
throw newErrorWithFilename;
}
throw err;
}
}
return import(file);
};
Expand Down
15 changes: 14 additions & 1 deletion test/integration/esm.spec.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';
var run = require('./helpers').runMochaJSON;
var helpers = require('./helpers');
var run = helpers.runMochaJSON;
var runMochaAsync = helpers.runMochaAsync;
var utils = require('../../lib/utils');
var args =
+process.versions.node.split('.')[0] >= 13 ? [] : ['--experimental-modules'];
Expand Down Expand Up @@ -38,6 +40,17 @@ describe('esm', function() {
});
});

it('should show file location when there is a syntax error in the test', async function() {
var fixture = 'esm/syntax-error/esm-syntax-error.fixture.mjs';
const err = await runMochaAsync(fixture, args, {stdio: 'pipe'}).catch(
err => err
);
expect(err.output, 'to contain', 'SyntaxError').and(
'to contain',
'esm-syntax-error.fixture.mjs'
);
});

it('should recognize esm files ending with .js due to package.json type flag', function(done) {
if (!utils.supportsEsModules(false)) return this.skip();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// This is intentionally a syntax error
it('should never run because of a syntax error here', => {
});

0 comments on commit 9878f32

Please sign in to comment.