UNPKG

vite-plugin-react-pages

Version:

<p> <a href="https://www.npmjs.com/package/vite-plugin-react-pages" target="_blank" rel="noopener"><img src="https://img.shields.io/npm/v/vite-plugin-react-pages.svg" alt="npm package" /></a> </p>

52 lines (46 loc) 1.46 kB
/// <reference types="remark-mdx" /> import type { Root } from 'mdast' import type { MdxjsEsm } from 'mdast-util-mdx' import { createJSXWithSpreadPropsNode, createNameSpaceImportNode, } from '../../utils/mdastUtils' export function DemoMdxPlugin() { return transformer function transformer(tree: Root, file: any) { const children = tree.children const addImports: MdxjsEsm[] = [] children.forEach((child, index) => { // find jsx node like: <Demo src="srcValue" /> if (child.type === 'mdxJsxFlowElement' && child.name === 'Demo') { const srcAttr = child.attributes.find( (attr) => attr.type === 'mdxJsxAttribute' && attr.name === 'src' && typeof attr.value === 'string' ) const srcValue = srcAttr?.value if (srcValue) { const nextIndex = addImports.length const varName = `_demo${nextIndex}` // add import: // import * as varName from "${srcValue}?demo" addImports.push( createNameSpaceImportNode({ name: varName, from: `${srcValue}?demo`, }) ) // replace this node with: // <Demo {...varName} /> children.splice( index, 1, createJSXWithSpreadPropsNode({ Component: 'Demo', props: varName }) ) } } }) children.unshift(...addImports) } }