我正在用nodejs和express编写一些代码,我需要在继续导入模块之前执行一些代码。 我的整个应用程序已设置并使用带有 import 的模块而不是 require,并且我无法更改此设置。
为了让一些 npm 包正常工作,我必须在继续导入模块之前运行它们。使用 commonJS 和 require () 可以完美地工作,但是使用 import 就不行了。
即使我颠倒模块的顺序或者在不同的文件中调用它们,它们都会首先加载,然后才执行我的代码。
示例 开始.js
import { mustBeLoadedAfterCode } from './second.js';
// some code here I need to execute first
第二个.js
import { mustBeLoadedAtTheEnd } from './third.js';
// some code here to execute at the end
在我的所有测试中,我的代码只有在导入“second.js”及其所有相关导入之后才会执行。
有什么想法吗?
最佳答案
我找到了使用动态导入的解决方案:
let module = await import('./module.js');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports
关于javascript - 执行代码后 Node 导入模块(或ESM动态导入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64978253/