fix: handle YAML front matter block (#3802)
This commit is contained in:
1 parent
5008836dc2
commit
a3bf378259
9 files changed
+147
-5
No files matched your search
@@ -1,6 +1,7 @@
|
||||
"use strict";
|
||||
|
||||
const createError = require("../common/parser-create-error");
|
||||
const grayMatter = require("gray-matter");
|
||||
|
||||
function parseSelector(selector) {
|
||||
// If there's a comment inside of a selector, the parser tries to parse
|
||||
@@ -189,7 +190,11 @@ function parseNestedCSS(node) {
|
||||
};
|
||||
}
|
||||
}
|
||||
if (node.type && typeof node.value === "string") {
|
||||
if (
|
||||
node.type &&
|
||||
node.type !== "css-comment-yaml" &&
|
||||
typeof node.value === "string"
|
||||
) {
|
||||
try {
|
||||
if (node.value.endsWith(DEFAULT_SCSS_DIRECTIVE)) {
|
||||
node.default = true;
|
||||
@@ -226,7 +231,7 @@ function parseNestedCSS(node) {
|
||||
return node;
|
||||
}
|
||||
|
||||
function parseWithParser(parser, text) {
|
||||
function parseWithParser(parser, text, frontMatter) {
|
||||
let result;
|
||||
try {
|
||||
result = parser.parse(text);
|
||||
@@ -236,6 +241,14 @@ function parseWithParser(parser, text) {
|
||||
}
|
||||
throw createError("(postcss) " + e.name + " " + e.reason, { start: e });
|
||||
}
|
||||
|
||||
if (Object.keys(frontMatter.data).length > 0) {
|
||||
result.nodes.unshift({
|
||||
type: "comment-yaml",
|
||||
value: grayMatter.stringify("", frontMatter.data).replace(/\s$/, "")
|
||||
});
|
||||
}
|
||||
|
||||
const prefixedResult = addTypePrefix(result, "css-");
|
||||
const parsedResult = parseNestedCSS(prefixedResult);
|
||||
return parsedResult;
|
||||
@@ -269,15 +282,22 @@ function parse(text, parsers, opts) {
|
||||
? opts.parser === "scss"
|
||||
: IS_POSSIBLY_SCSS.test(text);
|
||||
|
||||
const frontMatter = grayMatter(text);
|
||||
const normalizedText = frontMatter.content;
|
||||
|
||||
try {
|
||||
return parseWithParser(requireParser(isSCSS), text);
|
||||
return parseWithParser(requireParser(isSCSS), normalizedText, frontMatter);
|
||||
} catch (originalError) {
|
||||
if (hasExplicitParserChoice) {
|
||||
throw originalError;
|
||||
}
|
||||
|
||||
try {
|
||||
return parseWithParser(requireParser(!isSCSS), text);
|
||||
return parseWithParser(
|
||||
requireParser(!isSCSS),
|
||||
normalizedText,
|
||||
frontMatter
|
||||
);
|
||||
} catch (_secondError) {
|
||||
throw originalError;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user