Es6 commonJS模块化导入导出

Es6js模块化导入导出

写一个可到处文件exportTest.js

var name="牛";
var age=22;
var person={
    name:"小明",
    age:20
}
function run(){
     console.log("我跑的很快")
}
class student{
    function study(){
        console.log("I study well");
    }

}

//把此文件当做模块导出
export {name,age,person,run,student}

//还可以默认不起名字,但是只能存在一个default
export default const allAame="牛宝宝"

写一个可导入的文件importTest.js

//第一种:可导入所需要的
import {name,age,run} from "./exportTest.js"
//第二种:也可把exportTest当做对象导入
import * as exportTest from  "./exportTest.js"

//第三种:导入默认的allName
import  allName from "./exportTest.js"

//使用第二种
console.log("testExport.name"+testExport.name);
const student =new testExport.student();
console.log("testExport.student"+student.study());

commonjs导入导出

导出:

function sub(num1,num2){
    return num1+num2;
}

export {sub}

导入:

import {sub} from "./mathUtil.js"; 

//const math = require('./mathUtil.js')
console.log("2+3="+sub(2,3));