【发布时间】:2018-08-01 14:10:43
【问题描述】:
我已将我的项目迁移到 ESM,因此我在 nodejs 中的所有文件中都使用了 .mjs。
以前在 CommonJs 中,我可能需要一个位于 ES6 类函数中间的文件,以便在需要时仅加载它。
module.exports = class Core{
constructor() {
this.init = this._init.bind(this)
return this.init()
}
async _init(){
const module = require('module')
//use required file/module here
}
}
但是现在当使用 Michael Jackson Scripts a.k.a .mjs 时,我无法按需导入文件:
import Koa from 'koa'
export default = class Core{
constructor() {
this.init = this._init.bind(this)
return this.init()
}
async _init(){
import module from 'module'
//use imported file/module here
}
}
我的应用程序有许多文件/模块不会立即使用,并且将来可以随时添加更多,因此在文件开头对导入进行硬编码不是一种选择。
有没有办法在需要时按需动态导入文件?
【问题讨论】:
-
Dynamic import 仍然只是一个提议。我不知道目前有哪些浏览器支持它。
-
如果您的环境仍然支持,您仍然可以使用
require,否则使用动态import。 -
@Bergi 不能使用 require,我正在运行带有
--experimental-modules标志的 nodejs
标签: node.js ecmascript-6 es6-modules