Skip to content

Commit 28f9869

Browse files
authored
feat(json): log the filename when JSON.parse fails (#417)
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.
1 parent 7ae5390 commit 28f9869

File tree

2 files changed

+32
-17
lines changed

2 files changed

+32
-17
lines changed

packages/json/src/index.js

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,23 @@ export default function json(options = {}) {
1111
transform(json, id) {
1212
if (id.slice(-5) !== '.json' || !filter(id)) return null;
1313

14-
return {
15-
code: dataToEsm(JSON.parse(json), {
16-
preferConst: options.preferConst,
17-
compact: options.compact,
18-
namedExports: options.namedExports,
19-
indent
20-
}),
21-
map: { mappings: '' }
22-
};
14+
try {
15+
const parsed = JSON.parse(json);
16+
return {
17+
code: dataToEsm(parsed, {
18+
preferConst: options.preferConst,
19+
compact: options.compact,
20+
namedExports: options.namedExports,
21+
indent
22+
}),
23+
map: { mappings: '' }
24+
};
25+
} catch (err) {
26+
const message = 'Could not parse JSON file';
27+
const position = parseInt(/[\d]/.exec(err.message)[0], 10);
28+
this.warn({ message, id, position });
29+
return null;
30+
}
2331
}
2432
};
2533
}

packages/json/test/test.js

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -73,14 +73,21 @@ test('handles JSON objects with no valid keys (#19)', async (t) => {
7373
});
7474

7575
test('handles garbage', async (t) => {
76-
const bundle = async () =>
77-
rollup({
78-
input: 'fixtures/garbage/main.js',
79-
plugins: [json()]
80-
});
81-
82-
const error = await t.throwsAsync(bundle);
83-
t.is(error.message.indexOf('Unexpected token o'), 0);
76+
const warns = [];
77+
78+
await rollup({
79+
input: 'fixtures/garbage/main.js',
80+
plugins: [json()],
81+
onwarn: (warning) => warns.push(warning)
82+
}).catch(() => {});
83+
84+
const [{ message, id, position, plugin }] = warns;
85+
86+
t.is(warns.length, 1);
87+
t.is(plugin, 'json');
88+
t.is(position, 1);
89+
t.is(message, 'Could not parse JSON file');
90+
t.regex(id, /(.*)bad.json$/);
8491
});
8592

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

0 commit comments

Comments
 (0)