首页 > 解决方案 > 如何将javascript函数导出为模块

问题描述

我已经导出了一个函数并在 Javascript 中导入了它,但我可以访问其中的函数的唯一方法是像这样键入它:

myModule.mainFunc().func1()

但我想要实现的更像是这样的:

myModule.mainFunc.func1()

目前,如果我尝试像这样引用它,它会给出错误。

我尝试将函数的值作为对象返回,但它仍然需要我将其作为函数调用。

function greet() {

    var hello = () => {
        console.log("hello there");
    };

    var hi = () => {
        console.log("hi there");
    };

    return { hello: hello, hi: hi };  // I've tried this doing it like this 
}

export default {greet};

这是我导入它的方式:

import greetings from "./index.js";

greetings.greet().hello()

标签: javascriptfunctionimportmoduleexport

解决方案


您不能将函数内部定义的greet函数引用为

myModule.mainFunc.func1()

因为它本身myModule.mainFunc就是一个greet函数。您要导入的是调用greet函数的结果。

您可以greet通过将函数设为IIFE (Immediately Invoked Function Expression). 这样做将在定义函数后立即执行该函数。

const greet = (function() {

    var hello = () => {
        console.log("hello there");
    };

    var hi = () => {
        console.log("hi there");
    };

    return { hello, hi };
})();

export default { greet };

现在当你导出时greet,你不是导出greet函数,而是调用greet函数的结果,它是一个有两个函数的对象,hellohi


推荐阅读