222
schangxiang@126.com
2025-04-30 9bec4dcae002f36aa23231da11cb03a156b40110
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
72
73
74
import path from 'path'
const isWin = process.platform === 'win32'
const fileRegex = /\.(ts)$/
const basePath = path.resolve(process.cwd(), './src/widgets')
// @ts-ignore
const filePath = isWin ? basePath.replaceAll('\\', '/') : basePath
const regex = new RegExp(`${filePath}/([^/]*)/index.ts`)
const NOT_PAGE = 'notPage:true'
/**
 * 提取关键字符
 * @param {*} code
 * @returns
 */
const parseCode = (code) => {
  const importRegion = code.match(/import[^]*?("|')(.*?)\1;/g)
  const exportDefaultRegion = code.match(/export default [\s\S]*?;/)
  const canvasView = code.match(/canvasView: ([^,]+),/)
  const canvasViewValue = canvasView ? canvasView[1] : ''
 
  const imports = importRegion ? importRegion.join('\n') : ''
  const exportDefault = exportDefaultRegion ? exportDefaultRegion[0] : ''
 
  return { imports, exportDefault, canvasView: canvasView[0], canvasViewValue }
}
 
/**
 * 合并处理代码
 * @param {*} param0
 * @param {*} originCode
 */
const mergeCodeString = (
  { imports, exportDefault, canvasView, canvasViewValue },
  originCode
) => {
  const code = `${imports}\n${exportDefault}`
  if (
    canvasView.includes('provider(') &&
    originCode.includes('provider/index')
  ) {
    return code
  }
 
  const providerCode = 'import { provider } from "@/provider/index";'
 
  const exportDefaultCode = exportDefault.replace(
    canvasView,
    `canvasView: provider(${canvasViewValue}),`
  )
  return `${imports}\n${providerCode}\n${exportDefaultCode}`
}
 
export default function VitePluginWidgetProvider(): any {
  return {
    name: 'vite-plugin-widget-provider',
    apply: 'build',
 
    transform(code, id) {
      if (fileRegex.test(id)) {
        if (regex.test(id)) {
          const codeData = parseCode(code)
          const transformCode = mergeCodeString(codeData, code)
          // const emptyCode = code.replaceAll(' ', '')
 
          const newCode = transformCode
          // const newCode = emptyCode.includes(NOT_PAGE) ? code : transformCode
          return {
            code: newCode,
            map: null, // 如果可行将提供 source map
          }
        }
      }
    },
  }
}