Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: liveDemo context no longer uses require for imports #2187

Merged
merged 9 commits into from
Aug 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "dumi",
"version": "2.4.7",
"version": "2.4.8-beta.3",
"description": "📖 Documentation Generator of React Component",
"keywords": [
"generator",
Expand Down
2 changes: 1 addition & 1 deletion src/client/theme-default/slots/SourceCodeEditor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ const SourceCodeEditor: FC<ISourceCodeEditorProps> = (props) => {
autoComplete="off"
autoCorrect="off"
autoSave="off"
spellcheck="false"
spellCheck="false"
/>
)
}
Expand Down
6 changes: 3 additions & 3 deletions src/features/compile/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,9 @@ export default (api: IApi) => {
const loaderPath = require.resolve('../../loaders/markdown');

// support require mjs packages(eg. element-plus/es)
memo.resolve.byDependency.set('commonjs', {
conditionNames: ['require', 'node', 'import'],
});
// memo.resolve.byDependency.set('commonjs', {
// conditionNames: ['require', 'node', 'import'],
// });

const loaderBaseOpts: Partial<IMdLoaderOptions> = {
techStacks,
Expand Down
68 changes: 54 additions & 14 deletions src/loaders/markdown/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ export type IMdLoaderOptions =
| IMdLoaderTextModeOptions
| IMdLoaderDemoIndexModeOptions;

interface IDemoDependency {
key: string;
specifier: string;
}

function getDemoSourceFiles(demos: IMdTransformerResult['meta']['demos'] = []) {
return demos.reduce<string[]>((ret, demo) => {
if ('resolveMap' in demo) {
Expand All @@ -68,6 +73,10 @@ function getDemoSourceFiles(demos: IMdTransformerResult['meta']['demos'] = []) {
}, []);
}

function isRelativePath(path: string) {
return path.startsWith('./') || path.startsWith('../');
}

function emitDefault(
this: any,
opts: IMdLoaderDefaultModeOptions,
Expand Down Expand Up @@ -132,10 +141,50 @@ function emitDemo(
ret: IMdTransformerResult,
) {
const { demos } = ret.meta;
const shareDepsMap: Record<string, string> = {};
const demoDepsMap: Record<string, Record<string, string>> = {};

demos?.forEach((demo) => {
if ('resolveMap' in demo && 'asset' in demo) {
const entryFileName = Object.keys(demo.asset.dependencies)[0];
demoDepsMap[demo.id] ??= {};
Object.keys(demo.resolveMap).forEach((key, index) => {
const specifier = `${demo.id.replace(/-/g, '_')}_deps_${index}`;
if (key !== entryFileName && !isRelativePath(key)) {
if (shareDepsMap[key]) {
demoDepsMap[demo.id][key] = shareDepsMap[key];
} else {
demoDepsMap[demo.id][key] = specifier;
shareDepsMap[key] = specifier;
}
} else if (isRelativePath(key)) {
demoDepsMap[demo.id][winPath(demo.resolveMap[key])] = specifier;
}
});
}
});

const dedupedDemosDeps = Object.entries(demoDepsMap).reduce<
IDemoDependency[]
>((acc, [, deps]) => {
return acc.concat(
Object.entries(deps)
.map(([key, specifier]) => {
const existingIndex = acc.findIndex((obj) => obj.key === key);
if (existingIndex === -1) {
return { key, specifier };
}
return undefined;
})
.filter((item) => item !== undefined),
);
}, []);
return Mustache.render(
`import React from 'react';
import '${winPath(this.getDependencies()[0])}?watch=parent';
import '${winPath(this.getDependencies()[0])}?watch=parent';
{{#dedupedDemosDeps}}
import * as {{{specifier}}} from '{{{key}}}';
{{/dedupedDemosDeps}}
export const demos = {
{{#demos}}
'{{{id}}}': {
Expand All @@ -150,6 +199,7 @@ export const demos = {
};`,
{
demos,
dedupedDemosDeps,
renderAsset: function renderAsset(this: NonNullable<typeof demos>[0]) {
// do not render asset for inline demo
if (!('asset' in this)) return 'null';
Expand Down Expand Up @@ -181,23 +231,13 @@ export const demos = {
) {
// do not render context for inline demo
if (!('resolveMap' in this) || !('asset' in this)) return 'undefined';

const entryFileName = Object.keys(this.asset.dependencies)[0];

// render context for normal demo
const context = Object.entries(this.resolveMap).reduce(
(acc, [key, path]) => ({
const context = Object.entries(demoDepsMap[this.id]).reduce(
(acc, [key, specifier]) => ({
...acc,
// omit entry file
...(key !== entryFileName
? {
[key]: `{{{require('${path}')}}}`,
}
: {}),
...{ [key]: `{{{${specifier}}}}` },
}),
{},
);

return JSON.stringify(context, null, 2).replace(/"{{{|}}}"/g, '');
},
renderRenderOpts: function renderRenderOpts(
Expand Down
Loading