2017-03-24 50 views
0

在我models文件夹我有很多类似的文件..我可以从FS中导出模块吗?

// Account.js 
module.exports = mongoose.model('Account', AccountSchema) 
... 
// Rules.js 
module.exports = mongoose.model('Rules', RulesSchema) 

在我index.js文件(同一文件夹./models)。 原因是查找在./models导出文件夹中的所有文件,并为名为出口

// index.js 
const mathJSFiles = /^[^index].*\.js$/gmi; 
fs.readdirSync('.') 
    .filter(file => file.search(mathJSFiles) >= 0) 
    .forEach(file => { 
    file = path.basename(file, '.js') 
    exports[file] = require(join(models, file)) 
    }) 

因此,在另一个文件main.js想做这样...

import * as Models from './models' 
Models.Account 

或者

import { Account } from './models' 

这可能吗?

+0

什么是'* as'?你只是将ES6与Commonjs模块混合?其实它应该与一个简单的'const models = require('./ models')' – Bergi

+0

是的,对不起。我改变了我的答案。 – ridermansb

回答

0

我会建议做一些这样的:

// main.js 
var glob = require('glob') 
    , path = require('path'); 

glob.sync('./models/**/*.js').forEach(function(file) { 
    require(path.resolve(file)); 
}); 
相关问题