index.ts 2.5 KB
Newer Older
dsyuan001's avatar
init  
dsyuan001 已提交
1 2
import seoPrerender from './render'
import childProcess from 'child_process'
dsyuan001's avatar
dsyuan001 已提交
3
import path from 'path'
dsyuan001's avatar
init  
dsyuan001 已提交
4 5 6

interface Config {
  puppeteer?: any // puppeteer一些配置
dsyuan001's avatar
dsyuan001 已提交
7
  routes?: string[] // 需要生成的路由地址
dsyuan001's avatar
init  
dsyuan001 已提交
8 9
  removeStyle?: boolean // 启用vite preview会自带有些样式,默认下移除
  callback?: Function
dsyuan001's avatar
dsyuan001 已提交
10
  htmlRoutes?: string[] // 处理public目录下的html文件
dsyuan001's avatar
init  
dsyuan001 已提交
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
}

const prerender = (config: Config) => {
  const cfgConfig = {
    outDir: '',
    mode: '',
    root: '',
    local: ''
  }
  return {
    name: 'vitePluginSeoPrerender',
    enforce: 'post',
    configResolved(cfg: any) {
      cfgConfig.outDir = cfg.build.outDir
      cfgConfig.mode = cfg.mode
      cfgConfig.root = cfg.root
    },
    buildEnd() {
      //console.log('buildEnd')
    },
dsyuan001's avatar
dsyuan001 已提交
31
    configureServer(server) {
dsyuan001's avatar
dev  
dsyuan001 已提交
32
      console.log('is build')
dsyuan001's avatar
dsyuan001 已提交
33 34 35
      const {watcher} = server
      if (config.htmlRoutes?.length) {
        watcher.on('change', (filePath) => {
dsyuan001's avatar
dev  
dsyuan001 已提交
36 37 38 39 40
          const relativePath = path.relative(server.config.root, filePath).replace('public', '').replace(/\\/g,'/')
          if (config.htmlRoutes.includes(relativePath)) {
            // 监听 public 目录下的 HTML 文件更改
            console.log('server',server)
          }
dsyuan001's avatar
dsyuan001 已提交
41 42 43
        })
      }
    },
dsyuan001's avatar
init  
dsyuan001 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    closeBundle() {
      if (!config?.routes?.length) {
        console.log('路由地址为空,请配置需预渲染的routes')
        return
      }
      // vite build 构建生产环境时才执行
      if (cfgConfig.mode !== 'production') {
        return
      }
      console.log('[vite-plugin-seo-prerender] is start..')
      const cProcess = childProcess.exec('vite preview', (err, stdout, stderr) => {
        if (err) {
          console.error('执行命令时发生错误:', err);
          return;
        }
      })
      let localUrl
      cProcess.stdout.on('data', async (data) => {
        const local = data.match(/http:\/\/(.*?)\//g)
        if (local && local.length && !localUrl) {
          //转义并去掉最后一个/
          localUrl = local[0].replace(/\x1B\[\d+m/g, '').slice(0, -1) // 控制台输出的有些会经过转义
          console.log('Local: ' + localUrl)
          cfgConfig.local = localUrl
          await seoPrerender(Object.assign(config, cfgConfig))
          // 在某个条件满足时,关闭进程退出
          cProcess.kill('SIGTERM')
          process.exit() // 关闭当前进程并退出
          localUrl = ''
        }
      })
    }
  }
}
export default prerender