index.ts 4.6 KB
Newer Older
dsyuan001's avatar
init  
dsyuan001 已提交
1
import childProcess from 'child_process'
dsyuan001's avatar
dsyuan001 已提交
2
import path from 'path'
dsyuan001's avatar
dsyuan001 已提交
3 4 5 6 7 8
import seoPrerender from './render'
import publicHtml from "./public"
import {Config} from "./types"
import {createServer} from 'vite';
import fs from 'fs'
import puppeteer from 'puppeteer'
dsyuan001's avatar
init  
dsyuan001 已提交
9 10


dsyuan001's avatar
dsyuan001 已提交
11
let pPage
dsyuan001's avatar
init  
dsyuan001 已提交
12 13 14 15 16
const prerender = (config: Config) => {
  const cfgConfig = {
    outDir: '',
    mode: '',
    root: '',
dsyuan001's avatar
dsyuan001 已提交
17 18
    local: '',
    base: ''
dsyuan001's avatar
init  
dsyuan001 已提交
19 20 21 22 23 24 25 26
  }
  return {
    name: 'vitePluginSeoPrerender',
    enforce: 'post',
    configResolved(cfg: any) {
      cfgConfig.outDir = cfg.build.outDir
      cfgConfig.mode = cfg.mode
      cfgConfig.root = cfg.root
dsyuan001's avatar
dsyuan001 已提交
27 28 29 30
      cfgConfig.base = cfg.base
    },
    async buildStart() {

dsyuan001's avatar
init  
dsyuan001 已提交
31 32
    },
    buildEnd() {
dsyuan001's avatar
dsyuan001 已提交
33 34 35 36 37 38 39 40 41 42 43 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
      console.log('buildEnd,没看到有触发')
    },
    async load(id) {
    },
    transform(code, id) {
      /*if (id.endsWith('.html')) {
        console.log('transform:',id)
      }*/
    },
    /*transformIndexHtml(html, tag) {
      //console.log('transform',html)
    },*/
    transformIndexHtml: {
      async transform(html, ctx) {
        console.log('transform')
        //console.log('html',html)
        //console.log('ctx',ctx)
        //ctx.moduleGraph.transformIndexHtml(html=>{})

      }
    },
    async handleHotUpdate({file, server}) {
      if (file.endsWith('.html')) {
        /*console.log('file:',server)
        // 启动一个浏览器服务
        if (!pPage) {
          const browser = await puppeteer.launch(Object.assign({headless: 'new'}, config.puppeteer || {}));
          pPage = await browser.newPage()
          await pPage.goto('http://127.0.0.1:5173')
          await pPage.setViewport({width: 1024, height: 768})
        }
        pPage.content()
          .then(html => {
            console.log('page content', html)
          })
          .catch(res => {
            console.log('catch', res)
          })*/
      }
dsyuan001's avatar
init  
dsyuan001 已提交
72
    },
dsyuan001's avatar
dsyuan001 已提交
73
    configureServer(server) {
dsyuan001's avatar
dsyuan001 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
      if (config.html?.routes?.length) {
        server.middlewares.use((req, res, next) => {
          //  console.log(server.moduleGraph)
          const baseUrl = req.url.replace(cfgConfig.base, '/')
          console.log('base',baseUrl)
          if (config.html.routes.includes(baseUrl)) {
            console.log(req.url)
            const module = server.moduleGraph.getModuleByUrl(req.url)
              .then(res => {
                console.log(res, 'okk')
              })

            const htmlContent = module ? module.content : '';
            res.setHeader('Content-Type', 'text/html')
            res.end('12');
            return;
dsyuan001's avatar
dev  
dsyuan001 已提交
90
          }
dsyuan001's avatar
dsyuan001 已提交
91
          next()
dsyuan001's avatar
dsyuan001 已提交
92 93
        })
      }
dsyuan001's avatar
dsyuan001 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
      // console.log('configureServer')
      //const {watcher} = server
      /*if (config.htmlRoutes?.length) {
        watcher.on('change', async (filePath) => {
          const relativePath = path.relative(server.config.root, filePath).replace('public', '').replace(/\\/g, '/')
          if (config.htmlRoutes.includes(relativePath)) {
            // 监听 public 目录下的指定 HTML 文件更改
            let hostPort = '' // 获取启用的服务ip地址端口
            const resolvedUrls = server.resolvedUrls
            for (const key in resolvedUrls) {
              if (resolvedUrls[key].length) {
                hostPort = resolvedUrls[key][0]
              }
            }
            await publicHtml(Object.assign(config,
              {hostPort: hostPort, filePath: filePath}), 'dev')
          }
        })
      }*/
dsyuan001's avatar
dsyuan001 已提交
113
    },
dsyuan001's avatar
init  
dsyuan001 已提交
114 115 116 117 118 119 120 121 122 123
    closeBundle() {
      if (!config?.routes?.length) {
        console.log('路由地址为空,请配置需预渲染的routes')
        return
      }
      // vite build 构建生产环境时才执行
      if (cfgConfig.mode !== 'production') {
        return
      }
      console.log('[vite-plugin-seo-prerender] is start..')
dsyuan001's avatar
dsyuan001 已提交
124
      const cProcess = childProcess.exec('vite preview', (err) => {
dsyuan001's avatar
init  
dsyuan001 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
        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