首页 > 解决方案 > 在 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();

只是补充一下,将来会在这些模块中添加更多的功能。

提前致谢!

标签: javascriptes6-modules

解决方案


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();

推荐阅读