Javascript 模块化主要有三种方案:
1、CommonJS// module add.js
module.exports = function add (a, b) { return a + b; }
// main.js
var {add} = require(’./math’);
// i hate sync
console.log('1 + 2 = ’ + add(1,2);
- AMD / CMD// module add.js
define(function () {
return {
add: function (a, b) add { return a + b; }
};
});
// main.js
require([‘add’], function (add) {
//i hate callback
console.log('1 + 2 = ’ + add(1,2);
});
3、ES6// module add.js
export function add (a, b) { return a + b; }
// main.js
// i hate static
import {add} from ‘add.js’;
关于题主描述中的:“在此想问下,JS中的function{}难道不是“块”吗? function和class以及module究竟有哪些区别呢?”答案是 function、class 和 module 没有相同点。虽然 JavaScript 不是基于 class 的面向对象语言,但是通过原型链可以模拟。(并且 ES6 提供了 class 关键字作为语法糖。)虽然 JavaScript 语言层面并没有在(ES6之前的)上提供模块化的支持,所谓支持 module 指的是类似 C 语言中的 include 或 Go 语言的 import 。(并且 ES6 提供了模块化,并且使用了 import 关键字。)
https://www.jianshu.com/p/858d3e270f26