import { compatDevServer } from '@builder/compat-webpack4' ; import { getHTMLByEntryName } from './utils/htmlCache' ; let afterCompiled ; function getHTML ( entryName ) { const html = getHTMLByEntryName ( entryName ) ; if ( html ) return html ; return 'Document Not Found.' ; } export default ( config ) => { const devServer = compatDevServer ( config . devServer ) ; const devServerBeforeHook = devServer . getValue ( 'onBeforeSetupMiddleware' ) ; devServer . setValue ( 'onBeforeSetupMiddleware' , ( app , server ) => { if ( ! server ) { server = app ; app = server . app ; } if ( typeof devServerBeforeHook === 'function' ) { devServerBeforeHook ( server ) ; } const compiler = server . compiler . compilers [ 0 ] ; const contextQueue = [ ] ; compiler . hooks . done . tapAsync ( 'ApiHistoryCallback' , ( stats , callback ) => { let context ; afterCompiled = true ; while ( ( context = contextQueue . shift ( ) ) ) { const { entryName , res } = context ; res . send ( getHTML ( entryName ) ) ; } callback ( ) ; } ) ; app . get ( /^\/?(?!\.(js|css|json))/ , ( req , res , next ) => { const path = req . url . split ( '?' ) [ 0 ] ; const matched = path . match ( /^\/(\S*?)\.html/ ) ; if ( ! matched ) { next ( ) ; return ; } const entryName = matched [ 1 ] ; if ( afterCompiled ) { res . send ( getHTML ( entryName ) ) ; } else { contextQueue . push ( { res , entryName , } ) ; } } ) ; } ) ; } ;