vite-plugin-uni-provider.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * @Author: wjc
  3. * @Date: 2024-07-10 11:21:52
  4. * @LastEditors: wjc
  5. * @LastEditTime: 2024-07-11 20:20:48
  6. * @Description:
  7. */
  8. import path from 'path'
  9. import c from 'picocolors'
  10. import normallize from 'normalize-path'
  11. export interface Options {
  12. pagesRE: RegExp
  13. name: string
  14. configFile: string
  15. pagesBasePath: string
  16. configPath: string
  17. pluginName: string
  18. DEBUG: boolean
  19. }
  20. export default function (options: Partial<Options> = {}) {
  21. let {
  22. pagesRE = /src[\/\\]pages[\/\\]((?!.+(component(s)?|static).+).)*\.vue$/,
  23. name = 'sys',
  24. pluginName = 'uni-provider',
  25. DEBUG = process.env.DEBUG,
  26. } = options
  27. return {
  28. name: 'vite-plugin-' + pluginName,
  29. enforce: 'pre',
  30. transform(code, id) {
  31. id = normalizePagePathFromBase(id)
  32. if (pagesRE.test(normalizePagePathFromBase(id))) {
  33. // 三种情况:
  34. // 1. 前后都存在页面根级组件 => 不做操作
  35. // 2. 页面根级组件只存在于第一行 => 第一行修正结束符,最后一行添加结束符
  36. // 3. 前后都不存在页面根级组件 => 第一行添加开始符,最后一行添加结束符
  37. // 其他情况直接语法报错,不需要处理
  38. let startTag = new RegExp(`\<${name}`).test(code)
  39. let endTag = new RegExp(`\<\/${name}`).test(code)
  40. if (startTag && !endTag)
  41. code = code
  42. .replace(new RegExp(`(?<=\<${name}.*?)(\/\>|>.*?\<\/${name}\>)`), '>')
  43. .replace(/([\s\S]*)(\<\/template\>)/, `$1</${name}>\n</template>`)
  44. if (!startTag && !endTag)
  45. code = code
  46. .replace('<template>', `<template>\n<${name}>`)
  47. .replace(/([\s\S]*)(\<\/template\>)/, `$1</${name}>\n</template>`)
  48. debug(c.yellow(id), `startTag: ${startTag}`, `endTag: ${endTag}`)
  49. }
  50. return { code, map: null }
  51. },
  52. }
  53. function normalizePagePathFromBase(file) {
  54. return normallize(path.relative(process.cwd(), file))
  55. }
  56. function debug(...args) {
  57. DEBUG &&
  58. console.log(
  59. c.dim(new Date().toLocaleTimeString()),
  60. c.bold(c.red(`[debug:${pluginName}]`)),
  61. ...args
  62. )
  63. }
  64. }