* Add JSON support This fixes https://github.com/prettier/prettier/issues/1973 by using [json-to-ast] to parse JSON, then converting the AST into a mostly-Babylon AST, so as to piggyback on the existing printer logic. Identifiers and literals are currently printed verbatim from the input, but this could be improved upon later (at least for literals, not sure about identifiers). [json-to-ast]: https://github.com/vtrushin/json-to-ast * Rename `json-to-ast` parser to `json` See https://github.com/prettier/prettier/pull/2173#discussion_r122574644 * json: Use createError to have a pretty error See https://github.com/prettier/prettier/pull/2173#discussion_r122574748 * json: Transform AST without mutations See https://github.com/prettier/prettier/pull/2173#discussion_r122574690
68 lines
1.5 KiB
JavaScript
68 lines
1.5 KiB
JavaScript
"use strict";
|
|
|
|
const path = require("path");
|
|
|
|
const parsers = {
|
|
get flow() {
|
|
return eval("require")("./parser-flow");
|
|
},
|
|
get graphql() {
|
|
return eval("require")("./parser-graphql");
|
|
},
|
|
get parse5() {
|
|
return eval("require")("./parser-parse5");
|
|
},
|
|
get babylon() {
|
|
return eval("require")("./parser-babylon");
|
|
},
|
|
get typescript() {
|
|
return eval("require")("./parser-typescript");
|
|
},
|
|
get postcss() {
|
|
return eval("require")("./parser-postcss");
|
|
},
|
|
get json() {
|
|
return eval("require")("./parser-json");
|
|
}
|
|
};
|
|
|
|
function resolveParseFunction(opts) {
|
|
if (typeof opts.parser === "function") {
|
|
return opts.parser;
|
|
}
|
|
if (typeof opts.parser === "string") {
|
|
if (parsers.hasOwnProperty(opts.parser)) {
|
|
return parsers[opts.parser];
|
|
}
|
|
try {
|
|
return eval("require")(path.resolve(process.cwd(), opts.parser));
|
|
} catch (err) {
|
|
throw new Error(`Couldn't resolve parser "${opts.parser}"`);
|
|
}
|
|
}
|
|
return parsers.babylon;
|
|
}
|
|
|
|
function parse(text, opts) {
|
|
const parseFunction = resolveParseFunction(opts);
|
|
|
|
try {
|
|
return parseFunction(text, parsers, opts);
|
|
} catch (error) {
|
|
const loc = error.loc;
|
|
|
|
if (loc) {
|
|
const codeFrame = require("babel-code-frame");
|
|
error.codeFrame = codeFrame.codeFrameColumns(text, loc, {
|
|
highlightCode: true
|
|
});
|
|
error.message += "\n" + error.codeFrame;
|
|
throw error;
|
|
}
|
|
|
|
throw error.stack;
|
|
}
|
|
}
|
|
|
|
module.exports = { parse };
|