|
| 1 | +import { dirname, relative, isAbsolute } from 'path' |
| 2 | +import { promises as fs, existsSync } from 'fs' |
| 3 | +import { notNullish, slash } from '@antfu/utils' |
| 4 | +import { Context } from './context' |
| 5 | +import { getVueVersion } from './options' |
| 6 | +import { getTransformedPath } from './utils' |
| 7 | + |
| 8 | +export async function generateIdeHelper(ctx: Context, root: string, filepath: string) { |
| 9 | + const imports: Record<string, string> = Object.fromEntries( |
| 10 | + Object.values({ |
| 11 | + ...ctx.componentNameMap, |
| 12 | + ...ctx.componentCustomMap, |
| 13 | + }) |
| 14 | + .map(({ path, name, importName }) => { |
| 15 | + if (!name) |
| 16 | + return undefined |
| 17 | + path = getTransformedPath(path, ctx) |
| 18 | + const related = isAbsolute(path) |
| 19 | + ? `./${relative(dirname(filepath), path)}` |
| 20 | + : path |
| 21 | + |
| 22 | + let entry = 'import ' |
| 23 | + if (importName) |
| 24 | + entry += `{ ${importName} as ${name} }` |
| 25 | + else |
| 26 | + entry += name |
| 27 | + entry += ` from '${slash(related)}';` |
| 28 | + return [name, entry] |
| 29 | + }) |
| 30 | + .filter(notNullish), |
| 31 | + ) |
| 32 | + |
| 33 | + if (!Object.keys(imports).length) |
| 34 | + return |
| 35 | + |
| 36 | + const originalContent = existsSync(filepath) ? await fs.readFile(filepath, 'utf-8') : '' |
| 37 | + |
| 38 | + const lines = Object.entries(imports) |
| 39 | + .sort((a, b) => a[0].localeCompare(b[0])) |
| 40 | + |
| 41 | + let code = `// generated by unplugin-vue-components |
| 42 | +// We suggest you to NOT commit this file into source control |
| 43 | +// Read more: https://github.com/antfu/unplugin-vue-components/issues/135 |
| 44 | +` |
| 45 | + |
| 46 | + if (getVueVersion() === 'vue3') { |
| 47 | + code += `import { createApp } from "vue"; |
| 48 | + |
| 49 | +${lines.map(line => line[1]).join('\n')} |
| 50 | +
|
| 51 | +const app = createApp({}); |
| 52 | +
|
| 53 | +${lines.map(line => `app.component('${line[0]}', ${line[0]})`).join('\n')} |
| 54 | +
|
| 55 | +app.mount("body"); |
| 56 | +
|
| 57 | +` |
| 58 | + } |
| 59 | + else { |
| 60 | + code += `import Vue from "vue"; |
| 61 | + |
| 62 | +${lines.map(line => line[1]).join('\n')} |
| 63 | +
|
| 64 | +${lines.map(line => `Vue.component('${line[0]}', ${line[0]});\nVue.component('Lazy${line[0]}', ${line[0]});`).join('\n')} |
| 65 | +
|
| 66 | +` |
| 67 | + } |
| 68 | + |
| 69 | + if (code !== originalContent) |
| 70 | + await fs.writeFile(filepath, code, 'utf-8') |
| 71 | +} |
0 commit comments