Skip to content

Commit

Permalink
fix:优化代码,增加错误提示
Browse files Browse the repository at this point in the history
  • Loading branch information
SunLxy committed May 9, 2022
1 parent c75388f commit 63d3360
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 39 deletions.
1 change: 1 addition & 0 deletions core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type CodeBlockData = {
export default function (source: string) {
const options = this.getOptions();
const result = getCodeBlockString(source, options.lang || ['tsx', 'jsx']);

return `
${result}
export default {
Expand Down
76 changes: 47 additions & 29 deletions core/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,24 @@ import remark from 'remark';

/** 转换 代码*/
const getProcessor = (scope: string) => {
const child = remark.parse(scope) as MarkDownTreeType;
return child.children;
try {
const child = remark.parse(scope) as MarkDownTreeType;
return child.children;
} catch (err) {
console.warn(err);
}
};

const getMeta = (meta: string | null): Record<string, string | boolean> => {
let metaData: Record<string, string | boolean> = {};
if (meta) {
const [metaItem] = /mdx:(.[\w|:]+)/i.exec(meta) || [];
const [_, field, val] = (metaItem || '').split(':').map((item) => item.trim());
metaData[field] = val || true;
try {
if (meta) {
const [metaItem] = /mdx:(.[\w|:]+)/i.exec(meta) || [];
const [_, field, val] = (metaItem || '').split(':').map((item) => item.trim());
metaData[field] = val || true;
}
} catch (err) {
console.warn(err);
}
return metaData;
};
Expand All @@ -27,23 +35,27 @@ const getMeta = (meta: string | null): Record<string, string | boolean> => {
const getCodeBlock = (child: MarkDownTreeType['children'], lang: string[] = ['jsx', 'tsx']) => {
// 获取渲染部分
const codeBlock: Record<string | number, CodeBlockItemType> = {};
child.forEach((item) => {
if (item && item.type === 'code' && lang.includes(item.lang)) {
const line = item.position.start.line;
const metaData = getMeta(item.meta);
if (metaData.preview) {
let name = typeof metaData.preview === 'string' ? metaData.preview : line;
const funName = `BaseCode${line}`;
const returnCode = getTransformValue(item.value, `${funName}.${lang}`, funName);
codeBlock[line] = {
code: returnCode,
name,
language: item.lang,
value: item.value,
};
try {
child.forEach((item) => {
if (item && item.type === 'code' && lang.includes(item.lang)) {
const line = item.position.start.line;
const metaData = getMeta(item.meta);
if (metaData.preview) {
let name = typeof metaData.preview === 'string' ? metaData.preview : line;
const funName = `BaseCode${line}`;
const returnCode = getTransformValue(item.value, `${funName}.${lang}`, funName);
codeBlock[line] = {
code: returnCode,
name,
language: item.lang,
value: item.value,
};
}
}
}
});
});
} catch (err) {
console.warn(err);
}
return codeBlock;
};

Expand All @@ -52,13 +64,19 @@ const createStr = (codeBlock: Record<string | number, CodeBlockItemType>) => {
let baseCodeObjStr = ``;
let codeBlockValue = ``;
let languageStr = ``;
Object.entries(codeBlock).forEach(([key, item]) => {
const { code, value, language, name } = item;
baseCodeStr += `${code};\n`;
baseCodeObjStr += `${name}:BaseCode${key},\n`;
codeBlockValue += `${name}:${JSON.stringify(value)},\n`;
languageStr += `${name}:\`${language}\`,\n`;
});

try {
Object.entries(codeBlock).forEach(([key, item]) => {
const { code, value, language, name } = item;
baseCodeStr += `${code};\n`;
baseCodeObjStr += `${name}:BaseCode${key},\n`;
codeBlockValue += `${name}:${JSON.stringify(value)},\n`;
languageStr += `${name}:\`${language}\`,\n`;
});
} catch (err) {
console.warn(err);
}

let indexStr = `${baseCodeStr} const languages={${languageStr}};\n const codeBlock={${codeBlockValue}};\n const components={${baseCodeObjStr}}`;
return indexStr;
};
Expand Down
21 changes: 11 additions & 10 deletions core/src/utils/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@ export function babelTransform(input: string, filename: string) {
}

export const getTransformValue = (str: string, filename: string, funName: string) => {
const isReact = /import\x20+React(\x20+|[\x20+,]+({[a-zA-Z0-9,\s]+}|{})\x20+)from\x20+('|")react('|")/.test(str);
// 先判断 是否引入 react
const tran = isReact ? str : `import React from "react"\n ${str}`;
/** 先把默认导出 export default 进行替换 **/
const newCode = `${tran.replace(/export\x20+default/, 'const _default = ')}\n`;
const code = `${babelTransform(newCode, `${filename}`).code}\n return _react["default"].createElement(_default)`;

return `function ${funName}(){
${code}
}`;
try {
const isReact = /import\x20+React(\x20+|[\x20+,]+({[a-zA-Z0-9,\s]+}|{})\x20+)from\x20+('|")react('|")/.test(str);
// 先判断 是否引入 react
const tran = isReact ? str : `import React from "react"\n ${str}`;
/** 先把默认导出 export default 进行替换 **/
const newCode = `${tran.replace(/export\x20+default/, 'const _default = ')}\n`;
const code = `${babelTransform(newCode, `${filename}`).code}\n return _react["default"].createElement(_default)`;
return `function ${funName}(){\n${code}\n};`;
} catch (err) {
console.warn(err);
}
};

0 comments on commit 63d3360

Please sign in to comment.