gpt4 book ai didi

javascript - Node.js 中 ES6 模块的内联导入

转载 作者:行者123 更新时间:2023-12-02 23:59:53 24 4
gpt4 key购买 nike

在 Node.JS(CommonJS 模块)中管理模块的“旧方法”中,您可以执行以下操作:

Express.js 路由示例:app.use('/user', require("./user"));

当我使用 ES6 模块(导入、导出)并通过 babel 的 Node.JS 服务器转录时,如何执行此操作?

我不能只是这样做: app.use('/user', import {user} from './user');

最佳答案

有一种方法可以在 Node 中进行动态内联导入,详细信息如下: https://javascript.info/modules-dynamic-imports

这段代码对我有用:

let {default: foo} = await import('./foo.js');

这是我作为 Node 中数据库迁移工具的一部分编写的函数的工作示例。

const getMigrations = async (path) => {
const migrateDir = await fs.readdirSync(path);
const migrations = await Promise.all(migrateDir.map(async (filename) => {
let {default: migration} = await import(`${path}/${filename}`);
return migration;
}));
migrations.sort((a, b) => {
return a.seq - b.seq;
});
return migrations;
};

迁移示例如下:

export default {
seq: 1.1,
label: 'create user table',
sql: `
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
...
);
`
};

我在 package.json 中使用带有 "type": "module"的 Node v12.18.4。当我运行该脚本时,我收到一条警告,指出 ESM 模块加载器是实验性的,但它可以工作。但是,上面链接的页面上有一条注释:

Dynamic imports work in regular scripts, they don’t require script type="module".

我希望这有帮助。我相信您应该能够将其应用于您的问题。

关于javascript - Node.js 中 ES6 模块的内联导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55222881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com