Skip to content

Commit

Permalink
feat(json): log the filename when JSON.parse fails (#417)
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 authored Jun 3, 2020
1 parent 7ae5390 commit 28f9869
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 17 deletions.
26 changes: 17 additions & 9 deletions packages/json/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,23 @@ 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 {
const parsed = JSON.parse(json);
return {
code: dataToEsm(parsed, {
preferConst: options.preferConst,
compact: options.compact,
namedExports: options.namedExports,
indent
}),
map: { mappings: '' }
};
} catch (err) {
const message = 'Could not parse JSON file';
const position = parseInt(/[\d]/.exec(err.message)[0], 10);
this.warn({ message, id, position });
return null;
}
}
};
}
23 changes: 15 additions & 8 deletions packages/json/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,21 @@ test('handles JSON objects with no valid keys (#19)', async (t) => {
});

test('handles garbage', async (t) => {
const bundle = async () =>
rollup({
input: 'fixtures/garbage/main.js',
plugins: [json()]
});

const error = await t.throwsAsync(bundle);
t.is(error.message.indexOf('Unexpected token o'), 0);
const warns = [];

await rollup({
input: 'fixtures/garbage/main.js',
plugins: [json()],
onwarn: (warning) => warns.push(warning)
}).catch(() => {});

const [{ message, id, position, plugin }] = warns;

t.is(warns.length, 1);
t.is(plugin, 'json');
t.is(position, 1);
t.is(message, 'Could not parse JSON file');
t.regex(id, /(.*)bad.json$/);
});

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

0 comments on commit 28f9869

Please sign in to comment.