我正在解析目录中的所有模块,初始化它们,最后导出它们。有问题的模块是knex
这样的模型:
// schema/users.js
import createModel from './common'
const name = 'User'
const tableName = 'users'
const selectableProps = ['userId', 'name', 'email', 'updated_at', 'created_at']
export default knex => {
const model = createModel({
knex,
name,
tableName,
selectableProps,
})
return { ...model }
}
每个模型定义都使用公共部分进行扩展:
// schema/common.js
export default ({
knex = {},
name = 'name',
tableName = 'tablename',
selectableProps = [],
timeout = 1000,
}) => {
const findAll = () =>
knex
.select(selectableProps)
.from(tableName)
.timeout(timeout)
return {
name,
tableName,
selectableProps,
timeout,
findAll,
}
}
最后,所有模型都被初始化并导出:
// schema/index.js
import { readdir } from 'fs'
import { promisify } from 'util'
import { default as knex } from '../db'
let modules = {}
export default new Promise(async $export => {
const readFileAsync = promisify(readdir)
const getModels = async dir => await readFileAsync(dir)
const files = await getModels(__dirname)
for await (const file of files) {
if (file !== 'common.js' && file !== 'index.js') {
let mod = await import(__dirname + '/' + file).then(m => m.default(knex))
modules[mod.name] = mod
}
}
await $export(modules)
console.log(modules)
})
以上似乎有效,但我无法弄清楚如何从另一个文件中导入其中一个模块。我正在尝试按照以下方式做一些事情:
const User = async () => await import('../schema') // not working
或者
const User = (async () => await import('../schema'))() // not working
对此的任何帮助将不胜感激!