master
yutent 2024-12-18 11:37:15 +08:00
parent 1074b56bde
commit b5ffd5572d
2 changed files with 35 additions and 28 deletions

6
index.d.ts vendored
View File

@ -19,12 +19,10 @@ declare module '@gm5/core' {
use(middleware: Middleware | Installable, args?: any): this
install(module: Installable, args: any): this
preload(dir: string): this
listen(port?: number, callback?: () => void): this
}
export function preload(dir?: string): array
export function createApp(conf?: object): Five
}

View File

@ -53,6 +53,27 @@ class Five {
return this
}
async #preload(list) {
for (let item of list) {
let { name } = parse(item)
if (name.startsWith('.')) {
return
}
// 如果是目录,则默认加载index.js, 其他文件不加载
// 交由index.js自行处理, 用于复杂的应用
if (fs.isdir(item)) {
item = join(item, './index.js')
}
try {
let { default: Module } = await import(item)
this.#modules[name] = Module
} catch (err) {
console.error(err)
}
}
}
/*------------------------------------------------------------------------*/
get server() {
@ -102,6 +123,8 @@ class Five {
this.#middlewares.push(middleware)
} else if (typeof middleware === 'object' && typeof middleware.install === 'function') {
this.#install(middleware, args)
} else if (Array.isArray(middleware)) {
this.#preload(middleware)
} else {
throw TypeError('argument must be a function or installable object')
}
@ -116,31 +139,12 @@ class Five {
return this.#install(middleware, args)
}
// 预加载应用, 缓存以提高性能
/**
* 预加载应用, 缓存以提高性能
* @deprecated 请使用use方法, 将在下个版本中移除
*/
preload(dir) {
let list = fs.ls(dir)
if (list) {
list.forEach(item => {
let { name } = parse(item)
if (name.startsWith('.')) {
return
}
// 如果是目录,则默认加载index.js, 其他文件不加载
// 交由index.js自行处理, 用于复杂的应用
if (fs.isdir(item)) {
item = join(item, './index.js')
}
this.#modules[name] = import(item)
.then(r => r.default)
.catch(err => {
console.error(err)
return null
})
})
}
this.#preload(preload(dir))
return this
}
@ -184,6 +188,11 @@ class Five {
}
}
export function preload(dir) {
let list = fs.ls(dir) || []
return list
}
export function createApp(conf = {}) {
let app = new Five()
app.set(conf)