vite-plugin-uni-provider.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * @Author: wjc
  3. * @Date: 2024-07-10 11:21:52
  4. * @LastEditors: wjc
  5. * @LastEditTime: 2024-07-10 11:23: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. configFile = 'vite.config.js',
  25. pagesBasePath = 'src/pages',
  26. pluginName = 'uni-provider',
  27. DEBUG = process.env.DEBUG,
  28. } = options
  29. return {
  30. name: 'vite-plugin-' + pluginName,
  31. enforce: 'pre',
  32. transform(code, id) {
  33. id = normalizePagePathFromBase(id)
  34. if (pagesRE.test(normalizePagePathFromBase(id))) {
  35. // 三种情况:
  36. // 1. 前后都存在页面根级组件 => 不做操作
  37. // 2. 页面根级组件只存在于第一行 => 第一行修正结束符,最后一行添加结束符
  38. // 3. 前后都不存在页面根级组件 => 第一行添加开始符,最后一行添加结束符
  39. // 其他情况直接语法报错,不需要处理
  40. let startTag = new RegExp(`\<${name}`).test(code)
  41. let endTag = new RegExp(`\<\/${name}`).test(code)
  42. if (startTag && !endTag)
  43. code = code
  44. .replace(new RegExp(`(?<=\<${name}.*?)(\/\>|>.*?\<\/${name}\>)`), '>')
  45. .replace(/([\s\S]*)(\<\/template\>)/, `$1</${name}>\n</template>`)
  46. if (!startTag && !endTag)
  47. code = code
  48. .replace('<template>', `<template>\n<${name}>`)
  49. .replace(/([\s\S]*)(\<\/template\>)/, `$1</${name}>\n</template>`)
  50. debug(c.yellow(id), `startTag: ${startTag}`, `endTag: ${endTag}`)
  51. }
  52. return { code, map: null }
  53. },
  54. }
  55. function normalizePagePath(file) {
  56. return normallize(path.relative(pagesBasePath, file))
  57. }
  58. function normalizePagePathFromBase(file) {
  59. return normallize(path.relative(process.cwd(), file))
  60. }
  61. function log(...args) {
  62. console.log(c.dim(new Date().toLocaleTimeString()), c.bold(c.red(`[${pluginName}]`)), ...args)
  63. }
  64. function debug(...args) {
  65. DEBUG &&
  66. console.log(
  67. c.dim(new Date().toLocaleTimeString()),
  68. c.bold(c.red(`[debug:${pluginName}]`)),
  69. ...args
  70. )
  71. }
  72. }