node.js - ES6 类函数中的导入模块
问题描述
我已将我的项目迁移到 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 aka 时.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
}
}
我的应用程序有许多不会立即使用的文件/模块,并且将来总是可以添加更多,因此在文件开头对导入进行硬编码不是一种选择。
有没有办法在需要时按需动态导入文件?
解决方案
通过对这个答案的一些修改,我设法让它通过:
import Koa from 'koa'
export default = class Core{
constructor() {
this.init = this._init.bind(this)
return this.init()
}
async _init(){
const router = await import('./Router')
//use imported file/module here
}
}
或者,如果您对此感兴趣,则可以使用 Promise:
import('./router')
.then(something => {
//use imported module here
});
这适合我现在,直到规范最终确定并发货
推荐阅读
- ios - 如何从 XCode 项目创建“.ipa”?
- python - 来自 python 速成课程 web app django 项目
- typescript - Typescript. Optional arguments spreading crashing in v4
- arrays - VHDL - 脉动阵列:单元阵列中的单个单元在模拟中表现不同
- laravel - 输入按钮单击在 Laravel Dusk 中不起作用
- sql - SQL根据条件删除重复条目
- react-native - 如何从 react-native-render-html 中删除标签?
- javascript - 1 未定义,选择标签中的 optgroup
- python - 尝试为同一命令添加不同的冷却时间 (discord.py)
- sql - 找到最佳击球手位置的最大平均运行 - Oracle SQL