diff --git a/index.d.ts b/index.d.ts index 2571eda..d255532 100644 --- a/index.d.ts +++ b/index.d.ts @@ -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 } diff --git a/index.js b/index.js index 5c63859..7a8d145 100644 --- a/index.js +++ b/index.js @@ -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)