11// template.ts — 插件模板引擎
22import { readdir , readFile , writeFile , cp , rename , rm } from 'fs/promises'
3- import { join , resolve , dirname } from 'path'
3+ import { existsSync } from 'fs'
4+ import { join , dirname } from 'path'
45import { fileURLToPath } from 'url'
56
67export interface TemplateVars {
@@ -16,10 +17,33 @@ export interface TemplateVars {
1617 * 获取 CLI 包内置的 templates 目录路径
1718 */
1819export function getTemplatesDir ( ) : string {
19- // 支持 bun 直接运行和 build 后运行
20- const currentDir = dirname ( fileURLToPath ( import . meta. url ) )
21- // src/lib/template.ts -> ../../templates
22- return resolve ( currentDir , '..' , '..' , 'templates' )
20+ return resolveTemplatesDir ( import . meta. url )
21+ }
22+
23+ /**
24+ * 从运行模块位置向上查找包内 templates 目录。
25+ * 支持源码运行 (src/lib/template.ts) 和打包后运行 (dist/*.js)。
26+ */
27+ export function resolveTemplatesDir ( moduleUrl : string ) : string {
28+ let currentDir = dirname ( fileURLToPath ( moduleUrl ) )
29+
30+ while ( true ) {
31+ const candidate = join ( currentDir , 'templates' )
32+ if (
33+ existsSync ( join ( candidate , 'web' ) )
34+ && existsSync ( join ( candidate , 'server' ) )
35+ ) {
36+ return candidate
37+ }
38+
39+ const parentDir = dirname ( currentDir )
40+ if ( parentDir === currentDir ) break
41+ currentDir = parentDir
42+ }
43+
44+ throw new Error (
45+ `Unable to locate templates directory from ${ fileURLToPath ( moduleUrl ) } ` ,
46+ )
2347}
2448
2549/**
0 commit comments