import { Plugin } from 'vite'export default (enforce?: 'pre' | 'post'): Plugin => { return { name: 'apiPlugin', /** * * @param userConfig 用户配置的 config * @returns 可以异步返回,也可以同步返回 */ config(userConfig) { // 返回一些配置,和 userConfig 进行 merge return new Promise((resolve) => { resolve({ resolve: { alias: { assets: '/src/asstes', }, }, }) }) }, /** * @param config 最终会被使用的 config */ configResolved(config) { // console.log(config.resolve) }, /** * * @param server 服务实例 */ configureServer(server) { // console.log(server) // 和 express 中间件是一致的 // 如果不使用 return 返回一个函数, // server 中间件会在 vite 中间件之前执行 // 返回一个函数,会在 vite 之后执行 return () => { server.middlewares.use((req, res, next) => { if (req.originalUrl === '/test') { res.end('hello Vite Plugin') } else { next() } }) } }, /** * 处理 indexHtml 内容 * @param html index.html 的内容 */ transformIndexHtml(html) { // console.log(html) return html.replace('__TITLE__', '标题') }, /** * 处理模块热更新 * @param ctx */ handleHotUpdate(ctx) { // console.log(ctx) ctx.server.ws.send({ type: 'custom', event: 'test', data: { hello: 'hello', }, }) /* * 接收热更新的消息通知 if (import.meta.hot) { import.meta.hot.on('test', (val) => { console.log(val) }) } */ }, }}