1. import { Plugin } from 'vite'
    2. export default (enforce?: 'pre' | 'post'): Plugin => {
    3. return {
    4. name: 'apiPlugin',
    5. /**
    6. *
    7. * @param userConfig 用户配置的 config
    8. * @returns 可以异步返回,也可以同步返回
    9. */
    10. config(userConfig) {
    11. // 返回一些配置,和 userConfig 进行 merge
    12. return new Promise((resolve) => {
    13. resolve({
    14. resolve: {
    15. alias: {
    16. assets: '/src/asstes',
    17. },
    18. },
    19. })
    20. })
    21. },
    22. /**
    23. * @param config 最终会被使用的 config
    24. */
    25. configResolved(config) {
    26. // console.log(config.resolve)
    27. },
    28. /**
    29. *
    30. * @param server 服务实例
    31. */
    32. configureServer(server) {
    33. // console.log(server)
    34. // 和 express 中间件是一致的
    35. // 如果不使用 return 返回一个函数,
    36. // server 中间件会在 vite 中间件之前执行
    37. // 返回一个函数,会在 vite 之后执行
    38. return () => {
    39. server.middlewares.use((req, res, next) => {
    40. if (req.originalUrl === '/test') {
    41. res.end('hello Vite Plugin')
    42. } else {
    43. next()
    44. }
    45. })
    46. }
    47. },
    48. /**
    49. * 处理 indexHtml 内容
    50. * @param html index.html 的内容
    51. */
    52. transformIndexHtml(html) {
    53. // console.log(html)
    54. return html.replace('__TITLE__', '标题')
    55. },
    56. /**
    57. * 处理模块热更新
    58. * @param ctx
    59. */
    60. handleHotUpdate(ctx) {
    61. // console.log(ctx)
    62. ctx.server.ws.send({
    63. type: 'custom',
    64. event: 'test',
    65. data: {
    66. hello: 'hello',
    67. },
    68. })
    69. /*
    70. * 接收热更新的消息通知
    71. if (import.meta.hot) {
    72. import.meta.hot.on('test', (val) => {
    73. console.log(val)
    74. })
    75. }
    76. */
    77. },
    78. }
    79. }