我需要从ES6中的两个不同模块中导入同名函数。我应该在导入时使用as别名重命名每个函数还是使用Reveal Module Pattern?还是有更好的办法?
projects.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();
projects.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();
只需添加,将来将在这些模块中添加更多功能。
谢谢!
答案 0 :(得分:1)
显示模块模式是一种较早的模式,它早于ES6模块。目的是在私有功能范围内隐藏“模块”的细节,并防止污染全局范围。
对于ES6模块,这完全没有必要。您的问题确实是关于导出单个功能与单个界面的利弊。
请考虑使用以下方法:
projects.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();