import { Plugin } from 'vite' ; import { readFileSync , writeFileSync } from 'fs' ; import { resolve } from 'path' ; import { renderer } from './lib/index' ; export interface IRoute { component ? : string ; path ? : string ; routes ? : IRoute [ ] ; title ? : string ; redirect ? : string ; [ key ] : any ; } export interface IDynamicImportConfig { loading ? : string ; [ key ] : any ; } export type IDynamicImport = boolean | IDynamicImportConfig | undefined ; export type Options = { routes ? : Array < IRoute > ; dynamicImport ? : IDynamicImport ; routerBase ? : string ; entryPath ? : string ; containerID ? : string ; autoInjectScript ? : boolean ; } ; export default function useReactRouterConfig ( options ) { const { routes = [ ] , dynamicImport , entryPath = './.entry/' , containerID = 'root' , autoInjectScript = true , } = options ; const autoScriptReg = /<script autoInject="true".*?>.*?<\/script>/gi ; const autoInject = ( ) => { let content = readFileSync ( resolve ( process . cwd ( ) , './index.html' ) , 'utf-8' ) ; if ( content . search ( autoScriptReg ) === - 1 ) { content = content . replace ( '</body>' , `  <script autoInject="true" type="module" src="${ entryPath }/entry.tsx"></script>\n</body>` ) ; } else { content = content . replace ( autoScriptReg , `<script autoInject="true" type="module" src="${ entryPath }/entry.tsx"></script>` ) ; } writeFileSync ( resolve ( process . cwd ( ) , './index.html' ) , content ) ; } ; return { name : 'vite-plugin-react-router-config' , enforce : 'pre' , config ( config , { mode } ) { if ( mode === 'development' && autoInjectScript ) { autoInject ( ) ; } } , buildStart ( ) { renderer ( { routes , dynamicImport , containerID , entryPath } ) ; } , load ( id ) { if ( id === resolve ( process . cwd ( ) , './index.html' ) ) { const content = readFileSync ( resolve ( process . cwd ( ) , './index.html' ) , 'utf-8' ) ; return content . replace ( '</body>' , `  <script type="module" src="${ entryPath }/entry.tsx"></script>\n</body>` ) ; } return null ; } , } ; }