@1002522146
2017-08-21T06:01:57.000000Z
字数 1725
阅读 362
js模块化
模块化的进化过程
问题: 污染全局命名空间, 容易引起命名冲突/数据不安全
namespace模式 :
引入依赖: 通过函数形参来引入依赖模块
(function(window, module2){
var data = 'atguigu.com'
function foo() {
module2.xxx()
console.log('foo()'+data)
}
function bar() {
console.log('bar()'+data)
}
window.module = {foo}
})(window, module2)
模块化规范
基本语法:
exports.xxx = value
module.exports = value
引入模块 : require
var module = require('模块名/模块相对路径')
基本语法
require.config({
//基本路径
baseUrl : 'js/',
//标识名称与路径的映射
paths : {
'模块1' : 'modules/模块1',
'模块2' : 'modules/模块2',
'angular' : 'libs/angular',
'angular-messages' : 'libs/angular-messages'
},
//非AMD的模块
shim : {
'angular' : {
exports : 'angular'
},
'angular-messages' : {
exports : 'angular-messages',
deps : ['angular']
}
}
})
基本语法
定义暴露模块:
define(function(require, module, exports){
通过require引入依赖模块
通过module/exports来暴露模块
exports.xxx = value
})
使用模块seajs.use(['模块1', '模块2'])
基本语法
暴露一个对象:
export default 对象
暴露多个:
export var xxx = value1
export let yyy = value2
var xxx = value1
let yyy = value2
export {xxx, yyy}
引入使用模块 : import
default模块:
import xxx from '模块路径/模块名'
其它模块
import {xxx, yyy} from '模块路径/模块名'
import * as module1 from '模块路径/模块名'