简体   繁体   English

如何将 javascript function 导出为模块

[英]how to export javascript function as a module

I've exported a function and imported it in Javascript, but the only way i can access the functions inside it is by typing it like this:我已经导出了一个 function 并将其导入到 Javascript 中,但我可以访问其中的函数的唯一方法是像这样键入它:

myModule.mainFunc().func1()

But what i'm trying to achieve is more like this:但我想要实现的更像是这样的:

myModule.mainFunc.func1()

Currently it gives an error if i try to reference to it like this.目前,如果我尝试像这样引用它,它会给出错误。

I've tried returning the values of the functions as objects but it still needs me to call it as functions.我尝试将函数的值作为对象返回,但它仍然需要我将其作为函数调用。

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};

Here's how I'm importing it:这是我导入它的方式:

import greetings from "./index.js";

greetings.greet().hello()

You can't reference the functions defined inside greet function as您不能将 Greet greet中定义的函数引用为

myModule.mainFunc.func1()

because myModule.mainFunc is a greet function itself.因为myModule.mainFunc本身就是一个greet function 。 What you want to import is the result of calling greet function.您要导入的是调用greet function 的结果。

You can avoid invoking the greet function manually by making your function an IIFE (Immediately Invoked Function Expression) .您可以通过使 function 成为IIFE (Immediately Invoked Function Expression)来避免手动调用greet function。 Doing this will execute the function as soon as it is defined.这样做将在定义 function 后立即执行它。

const greet = (function() {

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

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

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

export default { greet };

Now when you export greet , you are not exporting greet function, but the result of calling greet function which is an object with two functions, hello and hi .现在当你导出greet时,你不是在导出greet function,而是调用greet function 的结果,它是一个 object 有两个功能, hellohi

define greet as an object将 greet 定义为 object

var greet = {
    hello: () => {
        console.log("hello there");
    },
    hi: () => {
        console.log("hi there");
    },
}

and access it like greet.hello()并像greet.hello()一样访问它

Which environment you're running your code?你在哪个环境运行你的代码? If it's NodeJS, make sure it supports ES6 Module as your current style of export and import.如果是 NodeJS,请确保它支持 ES6 模块作为您当前的导出和导入样式。 Normal NodeJS just supports CommonJS module.普通 NodeJS 只支持 CommonJS 模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM