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

Add file location when SyntaxError happens in ESM (fixes #4551) #4557

Merged
merged 3 commits into from Feb 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 23 additions & 1 deletion lib/esm-utils.js
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));
juergba marked this conversation as resolved.
Show resolved Hide resolved
} 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
@@ -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
@@ -0,0 +1,3 @@
// This is intentionally a syntax error
it('should never run because of a syntax error here', => {
});