前端模块化 (基于node.js)
ES5模块化
a.js
// 引入模块并调用
const b = require("./b.js")
b.f1();
b.f2()
b.js
// 定义模块
const f1 = function(){
console.log("f1")
}
const f2 = function(){
console.log("f2")
}
module.exports = {
f1,
f2
}
运行
>node a.js
ES6模块化 (方法1)该语法node不支持,需转为ES5
a.js
// 引入模块并调用
import {f1,f2} from './b.js'
f1();
f2()
b.js
// 定义模块
export function f1(){
console.log("f1")
}
export function f2(){
console.log("f2")
}
运行
>node a.js
ES6模块化 (方法2)该语法node不支持,需转为ES5
a.js
// 引入模块并调用
import b from './b.js'
b.f1();
b.f2()
b.js
// 定义模块
export default {
f1(){
console.log("f1")
},
f2(){
console.log("f2")
}
}
运行
>node a.js