commonjs使用 范例

commonJS 规范 千言万语不如一行代码

//example.js
var n = 1;
function sayHello( name ){
    var name = name || "Tom";
    return "Hello~"+name
}
function addFn(val){
    var val = val.x+val.y;
    return val
}
module.exports ={
    n:n,
    sayHello:sayHello,
    addFn:addFn
}

使用requier()引入使用

//main.js
var example = require('./example.js');
var addNum = {
    "x":10,
    "y":5
}
console.log( example )//查看example输出的对外模块接口;
console.log( example.n )//1;
console.log( example.sayHello("Jack") )// "Hello~ Jack";
console.log( example.addFn(addNum) ) //15;

参考地址:CommonJS规范

猜你喜欢

转载自blog.csdn.net/fly_wugui/article/details/80353195