【问题标题】:Can I export modules from FS?我可以从 FS 导出模块吗?
【发布时间】:2017-03-24 01:21:06
【问题描述】:

在我的models 文件夹我有很多文件,比如 ..

// 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'

这可能吗?

【问题讨论】:

  • 什么是* as?您只是将 ES6 与 Commonjs 模块混合在一起吗?实际上它应该适用于普通的const models = require('./models')
  • 是的,对不起。我改变我的答案。

标签: javascript node.js systemjs commonjs


【解决方案1】:

我建议您执行以下操作:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 2023-03-26
    • 2015-10-26
    • 2017-05-04
    • 1970-01-01
    相关资源
    最近更新 更多