javascript - 执行代码后 Node 导入模块(或ESM动态导入)

标签 javascript node.js node-modules

我正在用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

https://v8.dev/features/dynamic-import

关于javascript - 执行代码后 Node 导入模块(或ESM动态导入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64978253/

相关文章:

javascript - C++ 级别的 nodeJS 模块加载

javascript - Chrome 扩展不会为 Twitter 注入(inject) javascript

javascript - jQuery 密码强度检查器

wcf - 如何确定 WCF 服务期望什么?

node.js - AWS Cognito Node.JS 用户身份验证返回未知问题

javascript - Node 错误 : Cannot use import statement outside a module even though I'm not

javascript - 在不使用表单的情况下使用 ajax 上传图像

javascript - 如何一次导出所有常量?

javascript - Nodejs 编码为 Base64 字符串不起作用

docker - 如何测试 dockerignore 文件?