whitebear
whitebear

Reputation: 12455

How to write the common.js style

I have two functions

myFuncs.js

function funcA(e){
    console.log("FuncA:" + e);
}

function B(e){
     console.log("FuncB:" + e);
}

I would like to make common.js style module for these.

However I have some basic question.

I have read some articles and try to understand standard method.

In this case,

I need to make two files separately for each function A and B?

Are these are correct??

in funcA.js

(function(definition){

    funcA = definition();
})(function(){//
    'use strict';

    var funcA = function funcA(e){};

    funcA.prototype = {
        console.log("funcA"+ e);
    }

    return funcA;
});

in main.js

var funcA = require("funcA.js");

funcA.funcA("test"); 

Upvotes: 0

Views: 129

Answers (1)

Julian
Julian

Reputation: 2822

You can put them in one module with

// myFuncs.js
exports.funcA = function(e){
  console.log("FuncA:" + e);
}
// main.js
const myFuncs = require("./myFuncs")
myFuncs.funcA("test")

or export only one function

// funcA.js
module.exports = function(e){
  console.log("FuncA:" + e);
}
// main.js
const funcA = require("./funcA")
funcA("test");

You need a relative path, because require("funcA") will look in node_modules. And module names are usually lowercase and dash separated.

Upvotes: 1

Related Questions