Skip to content

Commit

Permalink
Throw parser error with code frames in loadConfig (#7451)
Browse files Browse the repository at this point in the history
  • Loading branch information
astralbody committed Dec 28, 2021
1 parent 26570dc commit 95e485c
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 1 deletion.
@@ -0,0 +1,7 @@
{
"plugins": {
"postcss-import": {},
"postcss-url": {}
"postcss-custom-properties": {}
}
}
46 changes: 46 additions & 0 deletions packages/core/integration-tests/test/postcss.js
Expand Up @@ -672,4 +672,50 @@ describe('postcss', () => {
},
);
});

it('should throw an error with code frame when .postcssrc is invalid', async function () {
let configFilePath = path.join(
__dirname,
'/integration/postcss-modules-config-invalid/.postcssrc',
);
let code = await inputFS.readFile(configFilePath, 'utf8');
await assert.rejects(
() =>
bundle(
path.join(
__dirname,
'/integration/postcss-modules-config-invalid/src/index.css',
),
),
{
name: 'BuildError',
diagnostics: [
{
codeFrames: [
{
code,
filePath: configFilePath,
language: 'json5',
codeHighlights: [
{
end: {
column: 5,
line: 5,
},
start: {
column: 5,
line: 5,
},
message: `JSON5: invalid character '\\"' at 5:5`,
},
],
},
],
message: 'Failed to parse .postcssrc',
origin: '@parcel/utils',
},
],
},
);
});
});
35 changes: 34 additions & 1 deletion packages/core/utils/src/config.js
Expand Up @@ -2,6 +2,7 @@

import type {ConfigResult, File, FilePath} from '@parcel/types';
import type {FileSystem} from '@parcel/fs';
import ThrowableDiagnostic from '@parcel/diagnostic';
import path from 'path';
import clone from 'clone';
import {parse as json5} from 'json5';
Expand Down Expand Up @@ -88,7 +89,39 @@ export async function loadConfig(
config = configContent;
} else {
let parse = opts?.parser ?? getParser(extname);
config = parse(configContent);
try {
config = parse(configContent);
} catch (e) {
if (extname !== '' && extname !== 'json') {
throw e;
}

let pos = {
line: e.lineNumber,
column: e.columnNumber,
};

throw new ThrowableDiagnostic({
diagnostic: {
message: `Failed to parse ${path.basename(configFile)}`,
origin: '@parcel/utils',
codeFrames: [
{
language: 'json5',
filePath: configFile,
code: configContent,
codeHighlights: [
{
start: pos,
end: pos,
message: e.message,
},
],
},
],
},
});
}
}

let output = {
Expand Down

0 comments on commit 95e485c

Please sign in to comment.