CommonJS

模块规范

CommonJS模块规范主要分为三部分:模块引用、模块定义、模块标识。

模块引用

var math = require("math");

带路径与不带路径的区别

上面 的例子中如果没有带路径,则引用的是当前所在目录下的node_modules目录。
如果引入的模块在其他路径,就需要使用到相对路径或绝对路径
var add = require('./add.js')

模块定义

  1. module对象:在每个模块中,module对象代表该模块本身
  2. export属性:module对象的一个属性,他向外提供接口
    假设:add.js代码入如下
function add(num1, num2){
    return num1+num2;
}

使用时会报错,需要对外暴露接口

function add(num1, num2){
    return num1+num2;
}
module.exports = add;

ES6

ES6发布的module并没有直接采用CommonJS,甚至连require都没有采用,也就是说require仍然只是node的一个私有的全局方法,module.exports也只是node私有的一个全局变量属性

export导出模块接口

两种形式 nameddefault
named形式

function cube(x) {
  return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
var graph = {
    options:{
        color:'white',
        thickness:'2px'
    },
    draw: function(){
        console.log('From graph draw function');
    }
}
export { cube, foo, graph };

引用

import { cube, foo, graph } from 'my-module';
graph.options = {
    color:'blue',
    thickness:'3px'
}; 
graph.draw();
console.log(cube(3)); // 27
console.log(foo);

default

// module "my-module.js"
export default function cube(x) {
  return x * x * x;
}

引用

import cube from 'my-module';
console.log(cube(3)); // 27

你可能感兴趣的:(CommonJS)