-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(umi-plugin): support to import external demo (#8)
- Loading branch information
1 parent
36b0496
commit e63d847
Showing
3 changed files
with
38 additions
and
3 deletions.
There are no files selected for viewing
32 changes: 32 additions & 0 deletions
32
packages/umi-plugin-father-doc/src/transformer/remark/externalDemo.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import fs from 'fs'; | ||
import path from 'path'; | ||
import visit from 'unist-util-visit'; | ||
|
||
const DEMO_TOKEN_EXP = /^\s*<code[^>]+src="?([^ ">]+)"?/; | ||
|
||
export default (options: { [key: string]: any } = {}) => (ast) => { | ||
visit(ast, 'html', (node) => { | ||
if (typeof node.value === 'string') { | ||
const matches = node.value.match(DEMO_TOKEN_EXP) || []; | ||
const demoPath = matches[1]; | ||
|
||
if (demoPath) { | ||
const absPath = demoPath.startsWith('/') ? demoPath : path.join(options.fileAbsDir, demoPath); | ||
|
||
if (fs.existsSync(absPath)) { | ||
// read external demo content and convert node to previewer | ||
const content = fs.readFileSync(absPath).toString(); | ||
|
||
node.type = 'previewer'; | ||
node.lang = absPath.match(/\.(\w+)$/)[1]; | ||
node.value = content; | ||
node.basePath = path.parse(absPath).dir; | ||
} else { | ||
throw new Error(`[External-Demo Error]: cannot find demo in ${absPath}`); | ||
} | ||
} else { | ||
throw new Error(`[External-Demo Error]: expected a code element with valid src property but got ${node.value}`); | ||
} | ||
} | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters