@@ -13,9 +13,34 @@ interface I18nResult {
1313
1414function parseI18n ( ) : I18nResult {
1515 // 本地的国际化文案
16- const localesDir = path . join ( __dirname , '../../locales' ) ;
16+ // 尝试多种路径来确保在不同运行环境下都能找到locales目录
17+ const possiblePaths = [
18+ path . join ( __dirname , '../../locales' ) ,
19+ path . join ( __dirname , '../../../locales' ) ,
20+ path . join ( __dirname , '../locales' ) ,
21+ path . join ( process . cwd ( ) , 'locales' ) ,
22+ path . join ( process . cwd ( ) , '../locales' ) ,
23+ path . join ( process . cwd ( ) , '../../locales' )
24+ ] ;
1725
18- if ( ! fs . existsSync ( localesDir ) ) {
26+ let localesDir = '' ;
27+ for ( const possiblePath of possiblePaths ) {
28+ if ( fs . existsSync ( possiblePath ) ) {
29+ localesDir = possiblePath ;
30+ break ;
31+ }
32+ }
33+
34+ if ( ! localesDir ) {
35+ // 如果在所有预期路径都找不到,则使用项目根目录的locales
36+ const projectRoot = findProjectRoot ( ) ;
37+ const fallbackPath = path . join ( projectRoot , 'locales' ) ;
38+ if ( fs . existsSync ( fallbackPath ) ) {
39+ localesDir = fallbackPath ;
40+ }
41+ }
42+
43+ if ( ! localesDir ) {
1944 return { messages : { } , locales : [ ] , defaultLocale : '' } ;
2045 }
2146
@@ -32,4 +57,34 @@ function parseI18n(): I18nResult {
3257 return { messages, locales, defaultLocale } ;
3358}
3459
35- export const { messages, locales, defaultLocale } = parseI18n ( ) ;
60+ function findProjectRoot ( ) : string {
61+ // 查找项目根目录(包含package.json的目录)
62+ let currentDir = __dirname ;
63+
64+ // 向上查找最多10层目录
65+ for ( let i = 0 ; i < 10 ; i ++ ) {
66+ const packageJsonPath = path . join ( currentDir , 'package.json' ) ;
67+ if ( fs . existsSync ( packageJsonPath ) ) {
68+ try {
69+ const packageJson = JSON . parse ( fs . readFileSync ( packageJsonPath , 'utf8' ) ) ;
70+ // 检查是否是主项目package.json
71+ if ( packageJson . name === 'reactpress' || packageJson . workspaces ) {
72+ return currentDir ;
73+ }
74+ } catch ( e ) {
75+ // 解析失败,继续向上查找
76+ }
77+ }
78+ const parentDir = path . dirname ( currentDir ) ;
79+ // 如果已经到达文件系统根目录,停止查找
80+ if ( parentDir === currentDir ) {
81+ break ;
82+ }
83+ currentDir = parentDir ;
84+ }
85+
86+ // 如果找不到项目根目录,返回当前工作目录
87+ return process . cwd ( ) ;
88+ }
89+
90+ export const { messages, locales, defaultLocale } = parseI18n ( ) ;
0 commit comments