module.exports that include all functions in a single line

前端 未结 6 1004
小鲜肉
小鲜肉 2021-02-05 10:19

This is a follow-up question to In Node.js, how do I "include" functions from my other files?

I would like to include an external js file that contains common

6条回答
  •  我在风中等你
    2021-02-05 10:54

    A really old question but I just had to solve the same issue myself. the solution I used was to define a Class inside the module to contain all my functions and simply export an instance of the class.

    classes.js looks like this:

    class TestClass
    {
       Function1() {
            return "Function1";
        } 
        Function2() {
            return "Function2";
        }
    }
    
    module.exports = new TestClass();
    

    app.js looks like this:

    const TestClass = require("./classes");
    console.log( TestClass.Function1);
    

    just keep adding more functions to the class and they will be exported :)

提交回复
热议问题