require
和import
;module.exports/exports
或者export/export default
;require
奇怪的是也可以使用import
????它们之间有何区别呢?于是有了菜鸟解惑的搜喽过程。。。。。。
// 导入
require("module");
require("../app.js");
// 导出
exports.getStoreInfo = function() {};
module.exports = someValue;
优点:
缺点:
?为什么浏览器不能使用同步加载,服务端可以?
// 定义
define("module", ["dep1", "dep2"], function(d1, d2) {...});
// 加载模块
require(["module", "../app"], function(module, app) {...});
require([module], callback);
第一个参数[module],是一个数组,里面的成员就是要加载的模块;第二个参数callback是加载成功之后的回调函。优点:
缺点:
require.js
RequireJS对模块的态度是预执行。由于 RequireJS 是执行的 AMD 规范, 因此所有的依赖模块都是先执行;即RequireJS是预先把依赖的模块执行,相当于把require提前了
factory 是一个函数,有三个参数,function(require, exports, module):
define(function(require, exports, module) {
var a = require(‘./a‘);
a.doSomething();
// 依赖就近书写,什么时候用到什么时候引入
var b = require(‘./b‘);
b.doSomething();
});
sea.js
:SeaJS对模块的态度是懒执行, SeaJS只会在真正需要使用(依赖)模块时才执行该模块// AMD
define([‘./a‘, ‘./b‘], function(a, b) { // 依赖必须一开始就写好
a.doSomething()
// 此处略去 100 行
b.doSomething()
...
});
// CMD
define(function(require, exports, module) {
var a = require(‘./a‘)
a.doSomething()
// 此处略去 100 行
var b = require(‘./b‘)
// 依赖可以就近书写
b.doSomething()
// ...
});
(function (window, factory) {
if (typeof exports === ‘object‘) {
module.exports = factory();
} else if (typeof define === ‘function‘ && define.amd) {
define(factory);
} else {
window.eventUtil = factory();
}
})(this, function () {
//module ...
});
ES6 模块设计思想:尽量的静态化、使得编译时就能确定模块的依赖关系,以及输入和输出的变量(CommonJS和AMD模块,都只能在运行时确定这些东西)。
// 导入
import "/app";
import React from “react”;
import { Component } from “react”;
// 导出
export function multiply() {...};
export var year = 2018;
export default ...
...
原文:https://www.cnblogs.com/bgd150809324/p/11283689.html