Skip to content

Commit

Permalink
fix(preset): external demo frontmatter HMR bug (#68)
Browse files Browse the repository at this point in the history
  • Loading branch information
PeachScript committed Mar 5, 2020
1 parent 6a2b0a5 commit 42a7a72
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions packages/preset-dumi/src/transformer/remark/externalDemo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import visit from 'unist-util-visit';
import transformer, { TransformResult } from '../index';

const DEMO_TOKEN_EXP = /<(code) ([^>]+?)\/?>/;
const fileWatchers: { [key: string]: fs.FSWatcher[] } = {};

/**
* simple parser for parse HTML attributes
Expand All @@ -22,7 +23,22 @@ function HTMLAttrParser(str: string): { [key: string]: any } {
return attrs;
}

function watchExternalDemoChange(demoPath: string, parentPath: string) {
fileWatchers[parentPath] = (fileWatchers[parentPath] || []).concat(
fs.watch(demoPath, () => {
// trigger parent file change to update frontmatter when demo file change
fs.writeFileSync(parentPath, fs.readFileSync(parentPath));
}),
);
}

export default function externalDemo() {
// clear exist watchers, use for unlink some demo from md file
fileWatchers[this.data('fileAbsPath')]?.forEach(watcher => {
watcher.close();
});
delete fileWatchers[this.data('fileAbsPath')];

return ast => {
visit(ast, 'html', (node, i, parent) => {
if (typeof node.value === 'string') {
Expand Down Expand Up @@ -63,6 +79,8 @@ export default function externalDemo() {
...result.config,
},
});

watchExternalDemoChange(absPath, this.data('fileAbsPath'));
} else {
throw new Error(`[External-Demo Error]: unsupported file type: ${lang}`);
}
Expand Down

1 comment on commit 42a7a72

@PeachScript
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#99

Please sign in to comment.