Skip to content

Commit

Permalink
fix: Fix loader example error issue.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaywcjlove committed May 25, 2022
1 parent 0f96f3c commit 61932f1
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 42 deletions.
20 changes: 14 additions & 6 deletions core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React from 'react';
import { PluginItem } from '@babel/core';
import { Options as RIOptions } from 'babel-plugin-transform-remove-imports';
import { getProcessor, getCodeBlock } from './utils';
import { LoaderDefinitionFunction } from 'webpack';
export * from './utils';

export type CodeBlockItem = {
Expand Down Expand Up @@ -41,18 +42,25 @@ export type Options = {
babelPlugins?: PluginItem[];
};

export default function (source: string) {
const codePreviewLoader: LoaderDefinitionFunction = function (source) {
const options: Options = this.getOptions();

const codeBlock = getCodeBlock(getProcessor(source), options);
let components = '';
Object.keys(codeBlock).forEach((key) => {
components += `${key}: (function() { ${codeBlock[key].code} })(),`;
});
let codeBlock = {} as CodeBlockData['data'];
try {
codeBlock = getCodeBlock(getProcessor(source), options, this.resourcePath);
Object.keys(codeBlock).forEach((key) => {
components += `${key}: (function() { ${codeBlock[key].code} })(),`;
});
} catch (error) {
this.emitError(error);
}

return `\nexport default {
components: { ${components} },
data: ${JSON.stringify(codeBlock, null, 2)},
source: ${JSON.stringify(source)}
}`;
}
};

export default codePreviewLoader;
46 changes: 23 additions & 23 deletions core/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,34 +63,34 @@ export const getMetaId = (meta: string = '') => {
export const isMeta = (meta: string = '') => meta && meta.includes('mdx:preview');

/** 获取需要渲染的代码块 **/
export const getCodeBlock = (child: MarkdownParseData['children'], opts: Options = {}): CodeBlockData['data'] => {
export function getCodeBlock(
child: MarkdownParseData['children'],
opts: Options = {},
resourcePath?: string,
): CodeBlockData['data'] {
const { lang = ['jsx', 'tsx'] } = opts;
// 获取渲染部分
const codeBlock: Record<string | number, CodeBlockItem> = {};
try {
child.forEach((item) => {
if (item && item.type === 'code' && lang.includes(item.lang)) {
const line = item.position.start.line;
const metaId = getMetaId(item.meta);
if (isMeta(item.meta)) {
let name = metaId || line;
const funName = `${FUNNAME_PREFIX}${name}`;
const returnCode = getTransformValue(item.value, `${funName}.${lang}`, opts);
codeBlock[name] = {
name,
meta: getURLParameters(item.meta),
code: returnCode,
language: item.lang,
value: item.value,
};
}
child.forEach((item) => {
if (item && item.type === 'code' && lang.includes(item.lang)) {
const line = item.position.start.line;
const metaId = getMetaId(item.meta);
if (isMeta(item.meta)) {
let name = metaId || line;
const funName = `${resourcePath}.${FUNNAME_PREFIX}${name}`;
const returnCode = getTransformValue(item.value, `${funName}.${item.lang}`, opts);
codeBlock[name] = {
name,
meta: getURLParameters(item.meta),
code: returnCode,
language: item.lang,
value: item.value,
};
}
});
} catch (err) {
console.warn(err);
}
}
});
return codeBlock;
};
}

/**
* `mdCodeModulesLoader` method for adding `markdown-react-code-preview-loader` to webpack config.
Expand Down
22 changes: 9 additions & 13 deletions core/src/utils/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,14 @@ import replaceExportDefault from 'babel-plugin-transform-replace-export-default'
import { Options } from '../';

export const getTransformValue = (str: string, filename: string, opts: Options) => {
try {
const plugins: PluginItem[] = [...(opts.babelPlugins || [])];
if (opts.removeImports) {
plugins.push([removeImports, opts.removeImports]);
}
const result = transform(str, {
filename,
presets: ['env', 'es2015', 'react', 'typescript'],
plugins: [...plugins, replaceExportDefault],
});
return result.code;
} catch (err) {
console.warn(err);
const plugins: PluginItem[] = [...(opts.babelPlugins || [])];
if (opts.removeImports) {
plugins.push([removeImports, opts.removeImports]);
}
const result = transform(str, {
filename,
presets: ['env', 'es2015', 'react', 'typescript'],
plugins: [...plugins, replaceExportDefault],
});
return result.code;
};

0 comments on commit 61932f1

Please sign in to comment.