Skip to content

Commit

Permalink
feat(json): log the filename when JSON.parse fails
Browse files Browse the repository at this point in the history
Helpful when debugging
Sometimes in a large codebase, a single comma buried in a gigantic json file can halt the entire build. This change ensures that users will more easily be able to find and fix those errors.
  • Loading branch information
bennypowers committed May 26, 2020
1 parent 867c699 commit 0efe962
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
24 changes: 15 additions & 9 deletions packages/json/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,21 @@ export default function json(options = {}) {
transform(json, id) {
if (id.slice(-5) !== '.json' || !filter(id)) return null;

return {
code: dataToEsm(JSON.parse(json), {
preferConst: options.preferConst,
compact: options.compact,
namedExports: options.namedExports,
indent
}),
map: { mappings: '' }
};
try {
return {
code: dataToEsm(JSON.parse(json), {
preferConst: options.preferConst,
compact: options.compact,
namedExports: options.namedExports,
indent
}),
map: { mappings: '' }
};
} catch (err) {
const error = new Error(`Could not parse ${id}`);
error.originalError = err;
throw error;
}
}
};
}
2 changes: 1 addition & 1 deletion packages/json/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ test('handles garbage', async (t) => {
});

const error = await t.throwsAsync(bundle);
t.is(error.message.indexOf('Unexpected token o'), 0);
t.regex(error.message, /Could not parse (.*)bad.json$/);
});

test('does not generate an AST', async (t) => {
Expand Down

0 comments on commit 0efe962

Please sign in to comment.