Skip to content

Commit

Permalink
feat: add removeImports/babelPlugins options.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaywcjlove committed May 11, 2022
1 parent 248cbba commit a1d95de
Show file tree
Hide file tree
Showing 6 changed files with 84 additions and 14 deletions.
23 changes: 22 additions & 1 deletion core/README-zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ npm i markdown-react-code-preview-loader -D

**第 ① 种方法,使用 mdCodeModulesLoader 方法**

`mdCodeModulesLoader` 用于在 webpack 配置添加 `markdown-react-code-preview-loader` 的方法。

```ts
// .kktrc.ts
import scopePluginOptions from '@kkt/scope-plugin-options';
Expand Down Expand Up @@ -67,7 +69,26 @@ export default (conf: Configuration, env: 'development' | 'production', options:

### options 参数

- lang: 需要解析代码块的语言,默认: `["jsx","tsx"]`
```ts
import { PluginItem } from '@babel/core';
import { Options as RIOptions } from 'babel-plugin-transform-remove-imports'
export type Options = {
/**
* 需要解析代码块的语言,默认: `["jsx","tsx"]`
*/
lang?: string[];
/**
* 删除过滤 imports 包;
* babel (babel-plugin-transform-remove-imports) 包的 option 设置
* https://github.com/uiwjs/babel-plugin-transform-remove-imports
*/
removeImports?: RIOptions;
/**
* 添加 babel 插件。
*/
babelPlugins?: PluginItem[];
}
```
## 项目中使用
Expand Down
22 changes: 21 additions & 1 deletion core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ After installing the dependency (loader), we need to configure the `loader` into

**① The first method, use the mdCodeModulesLoader method**

`mdCodeModulesLoader` method for adding `markdown-react-code-preview-loader` to webpack config.

```ts
// .kktrc.ts
import scopePluginOptions from '@kkt/scope-plugin-options';
Expand Down Expand Up @@ -67,7 +69,25 @@ export default (conf: Configuration, env: 'development' | 'production', options:

### options parameter

- lang: Language to parse code blocks, default: `["jsx","tsx"]`
```ts
import { PluginItem } from '@babel/core';
import { Options as RIOptions } from 'babel-plugin-transform-remove-imports'
export type Options = {
/**
* Language to parse code blocks, default: `["jsx","tsx"]`
*/
lang?: string[];
/**
* Option settings for the babel (babel-plugin-transform-remove-imports) package
* https://github.com/uiwjs/babel-plugin-transform-remove-imports
*/
removeImports?: RIOptions;
/**
* Add babel plugins.
*/
babelPlugins?: PluginItem[];
}
```
## Used in the project
Expand Down
1 change: 1 addition & 0 deletions core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
},
"dependencies": {
"@babel/standalone": "^7.17.11",
"babel-plugin-transform-remove-imports": "^1.7.0",
"remark": "~13.0.0"
},
"devDependencies": {
Expand Down
24 changes: 21 additions & 3 deletions core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { getCodeBlockString } from './utils';
import React from 'react';
import { PluginItem } from '@babel/core';
import { Options as RIOptions } from 'babel-plugin-transform-remove-imports';
import { getCodeBlockString } from './utils';
export * from './utils';

export type CodeBlockData = {
Expand All @@ -9,9 +11,25 @@ export type CodeBlockData = {
languages: Record<string | number, string>;
};

export type Options = {
/**
* Language to parse code blocks, default: `["jsx","tsx"]`
*/
lang?: string[];
/**
* Option settings for the babel (babel-plugin-transform-remove-imports) package
* https://github.com/uiwjs/babel-plugin-transform-remove-imports
*/
removeImports?: RIOptions;
/**
* Add babel plugins.
*/
babelPlugins?: PluginItem[];
};

export default function (source: string) {
const options = this.getOptions();
const result = getCodeBlockString(source, options.lang || ['tsx', 'jsx']);
const options: Options = this.getOptions();
const result = getCodeBlockString(source, options);

return `
${result}
Expand Down
14 changes: 8 additions & 6 deletions core/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
import { MarkDownTreeType, CodeBlockItemType } from './interface';
import { getTransformValue } from './transform';
import webpack from 'webpack';
export * from './interface';
import remark from 'remark';
export * from './interface';
import { Options } from '../';

/** 转换 代码*/
const getProcessor = (scope: string) => {
Expand All @@ -32,7 +33,8 @@ const getMeta = (meta: string | null): Record<string, string | boolean> => {
};

/** 获取需要渲染的代码块 **/
const getCodeBlock = (child: MarkDownTreeType['children'], lang: string[] = ['jsx', 'tsx']) => {
const getCodeBlock = (child: MarkDownTreeType['children'], opts: Options = {}) => {
const { lang = ['jsx', 'tsx'] } = opts;
// 获取渲染部分
const codeBlock: Record<string | number, CodeBlockItemType> = {};
try {
Expand All @@ -43,7 +45,7 @@ const getCodeBlock = (child: MarkDownTreeType['children'], lang: string[] = ['js
if (metaData.preview) {
let name = typeof metaData.preview === 'string' ? metaData.preview : line;
const funName = `BaseCode${line}`;
const returnCode = getTransformValue(item.value, `${funName}.${lang}`, funName);
const returnCode = getTransformValue(item.value, `${funName}.${lang}`, funName, opts);
codeBlock[line] = {
code: returnCode,
name,
Expand Down Expand Up @@ -81,15 +83,15 @@ const createStr = (codeBlock: Record<string | number, CodeBlockItemType>) => {
return indexStr;
};

export const getCodeBlockString = (scope: string, lang: string[] = ['jsx', 'tsx']) => {
export const getCodeBlockString = (scope: string, opts: Options = {}) => {
const children = getProcessor(scope);
const codeBlock = getCodeBlock(children, lang);
const codeBlock = getCodeBlock(children, opts);
const result = createStr(codeBlock);
return result;
};

/**
* 配置好markdown的loader
* 用于修改 webpack 配置 loader 的方法
* @param {webpack.Configuration} config webpack配置
* @param {string[]} lang 解析语言
* @returns {webpack.Configuration}
Expand Down
14 changes: 11 additions & 3 deletions core/src/utils/transform.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@
import { transform } from '@babel/standalone';
import { PluginItem } from '@babel/core';
import { Options } from '../';

export function babelTransform(input: string, filename: string) {
export function babelTransform(input: string, filename: string, opts: Options = {}) {
const plugins: PluginItem[] = [...(opts.babelPlugins || [])];
if (opts.removeImports) {
plugins.push(['babel-plugin-transform-remove-imports', opts.removeImports]);
}
return transform(input, {
filename,
presets: ['env', 'es2015', 'react', 'typescript'],
plugins: [...plugins],
});
}

export const getTransformValue = (str: string, filename: string, funName: string) => {
export const getTransformValue = (str: string, filename: string, funName: string, opts: Options) => {
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)`;
const tranCode = babelTransform(newCode, `${filename}`, opts).code;
const code = `${tranCode}\n return _react["default"].createElement(_default)`;
return `function ${funName}(){\n${code}\n};`;
} catch (err) {
console.warn(err);
Expand Down

0 comments on commit a1d95de

Please sign in to comment.