javascript - 在 ES6 模块中导入同名函数的最佳方法
问题描述
我需要从 ES6 中的两个不同模块导入同名函数。我应该在导入时使用 as 别名重命名每个函数还是使用显示模块模式?或者也许有更好的方法?
使用别名的解决方案
项目.module.js
function init() {
console.log("projects module initiated!");
}
export { init };
projects_steps.module.js
function init() {
console.log("project steps module initiated!");
}
export { init };
index.js
import { init as projectsInit } from "./projects.module.js";
import { init as projectStepsInit } from "./project_steps.module.js";
projectsInit();
projectStepsInit();
显示模块模式的解决方案
项目.module.js
var projects = (() => {
function init() {
console.log("projects module initiated!");
}
return {
init: init
};
})();
export { projects };
project_steps.module.js
var projectSteps = (() => {
function init() {
console.log("project steps module initiated!");
}
return {
init: init
};
})();
export { projectSteps };
index.js
import { projects } from "./projects.module.js";
import { projectSteps } from "./project_steps.module.js";
projects.init();
projectSteps.init();
只是补充一下,将来会在这些模块中添加更多的功能。
提前致谢!
解决方案
Revealing Module Pattern 是一种早于 ES6 模块的旧模式。其目的是在私有函数范围内隐藏“模块”的细节,并防止对全局范围的污染。
对于 ES6 模块,这是完全没有必要的。您的问题实际上是关于导出单个功能与单个界面的优缺点。
考虑改用以下方法:
项目.module.js
function init() {
console.log("projects module initiated!");
}
function foo() {
}
// export an object as the default, which will act as your interface
export default { init, foo };
projects_steps.module.js
function init() {
console.log("project steps module initiated!");
}
function foo() {
}
// you can still export individual functions where it makes sense
export function projectStepsThing() {
}
// if you don't want to export a default, then just set an object like so:
export const projectSteps = { init, foo };
index.js
import projects from "./projects.module.js";
import { projectSteps, projectStepsThing } from "./project_steps.module.js";
projects.init();
projects.foo();
projectSteps.init();
projectSteps.foo();
projectStepsThing();
推荐阅读
- php - PHP 表单结果到 Dompdf PDF
- xml - 使用 XSLT,如何从输出到单个文件的多个 xml 文件中获取属性?
- javascript - 将轮播项目传递给 Map 函数
- ios - 使用 Cocoapods 时找不到 FMDB 库
- ios - 授权失败:错误域=AKAuthenticationError Code=-7026 "(null)" UserInfo={AKClientBundleID=my bundle id}
- xmlstarlet - 使用 xmlstarlet 选择多个元素
- node.js - 使用 Sequelize 从 ec2 连接到 postgres RDS
- python - Python:如何删除列表中的数字
- node.js - 在 bot 框架中处理异步调用
- label - 如何将下标添加到观星表协变量标签?