Skip to content

Commit ec0af4a

Browse files
committed
feat: add jsTemplate for vite-plugin-amisr
1 parent 973c1ea commit ec0af4a

File tree

2 files changed

+24
-15
lines changed

2 files changed

+24
-15
lines changed

packages/vite-plugin-amisr/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "vite-plugin-amisr",
3-
"version": "0.0.1",
3+
"version": "0.0.2",
44
"type": "module",
55
"description": "将 amis json 文件转换为 react 组件",
66
"main": "dist/index.cjs.js",

packages/vite-plugin-amisr/src/index.ts

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,25 @@ import type {Plugin} from 'vite';
22
import fs from 'fs';
33
import path from 'path';
44

5-
export interface AMISROptions {}
5+
export interface AMISROptions {
6+
jsTemplate?: string;
7+
}
8+
9+
const defaultJsTemplate = [
10+
`import React from 'react';`,
11+
`import {useRenderOptionsContext, render} from 'amis-core';`,
12+
`import {useParams} from "react-router-dom";`,
13+
`const schema = {{JSON_CODE}}`,
14+
`export default function AMISPage(props) {`,
15+
` const options = useRenderOptionsContext();`,
16+
` const params = useParams();`,
17+
` return React.createElement(React.Fragment, null, render(schema, {params, ...props}, options));`,
18+
`}`
19+
].join('\n');
620

7-
export default function vitePluginAmisR({}: AMISROptions = {}): Plugin {
21+
export default function vitePluginAmisR({
22+
jsTemplate = defaultJsTemplate
23+
}: AMISROptions = {}): Plugin {
824
const match = (id: string) => {
925
return /(?:amis|dslpage)\.json(?:$|\?)/.test(id);
1026
};
@@ -38,20 +54,13 @@ export default function vitePluginAmisR({}: AMISROptions = {}): Plugin {
3854
? real
3955
: path.resolve(process.cwd(), real);
4056

41-
const code = await fs.promises.readFile(filePath, 'utf8');
42-
43-
const codes = [
44-
`import React from 'react';`,
45-
`import {useRenderOptionsContext, render} from 'amis-core';`,
46-
`const schema = ${code};`,
47-
`export default function AMISPage(props) {`,
48-
` const options = useRenderOptionsContext();`,
49-
` return React.createElement(React.Fragment, null, render(schema, props, options));`,
50-
`}`
51-
];
57+
const jsonCode = await fs.promises.readFile(filePath, 'utf8');
58+
const code = jsTemplate
59+
.replace('{{JSON_CODE}}', jsonCode)
60+
.replace('{{JSON_CONTENTS}}', jsonCode);
5261

5362
return {
54-
code: codes.join('\n')
63+
code: code
5564
};
5665
}
5766
};

0 commit comments

Comments
 (0)