|
| 1 | +import MagicString from 'magic-string' |
| 2 | +import type { Plugin } from 'vite' |
| 3 | + |
| 4 | +function pascalCase(str: string) { |
| 5 | + const camelCaseStr = str.replace(/-(\w)/g, (_, c) => (c ? c.toUpperCase() : '')) |
| 6 | + return camelCaseStr.charAt(0).toUpperCase() + camelCaseStr.slice(1) |
| 7 | +} |
| 8 | + |
| 9 | +const resolveVue = (code: string, s: MagicString) => { |
| 10 | + const results: any = [] |
| 11 | + |
| 12 | + for (const match of code.matchAll(/_resolveComponent[0-9]*\("(.+?)"\)/g)) { |
| 13 | + const matchedName = match[1] |
| 14 | + if (match.index != null && matchedName && !matchedName.startsWith('_')) { |
| 15 | + const start = match.index |
| 16 | + const end = start + match[0].length |
| 17 | + results.push({ |
| 18 | + rawName: matchedName, |
| 19 | + replace: (resolved: string) => s.overwrite(start, end, resolved) |
| 20 | + }) |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + return results |
| 25 | +} |
| 26 | + |
| 27 | +const findComponent = (rawName: string, name: string, s: MagicString) => { |
| 28 | + if (!name.match(/^Tiny[a-zA-Z]/)) { |
| 29 | + return |
| 30 | + } |
| 31 | + s.prepend(`import ${name} from '@opentiny/vue-${rawName.slice(5)}';\n`) |
| 32 | +} |
| 33 | + |
| 34 | +const transformCode = (code) => { |
| 35 | + const s = new MagicString(code) |
| 36 | + const results = resolveVue(code, s) |
| 37 | + |
| 38 | + for (const { rawName, replace } of results) { |
| 39 | + const name = pascalCase(rawName) |
| 40 | + findComponent(rawName, name, s) |
| 41 | + replace(name) |
| 42 | + } |
| 43 | + |
| 44 | + const result = s.toString() |
| 45 | + return result |
| 46 | +} |
| 47 | + |
| 48 | +export default function vitePluginAutoImport(): Plugin { |
| 49 | + return { |
| 50 | + name: '@opentiny/auto-import', |
| 51 | + |
| 52 | + transform(code, id) { |
| 53 | + // 不处理node_modules内的依赖 |
| 54 | + if (/\.(?:vue)$/.test(id) && !/(node_modules)/.test(id)) { |
| 55 | + return { |
| 56 | + code: transformCode(code), |
| 57 | + map: null |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments