模块化
-
避免带来全局污染
-
require.js 的使用
//util.js define(function() { var util = { getFormatDate: function(date, type) { if (type === 1) { return '1-1' } if (type === 2) { return '1月1' } } } return util })
//a-util.js define(['./util.js'], function(util) { return { aGetFormatDate: function(date) { return util.getFormatDate() } } })
//a.js define(['./a-util.js', function(aUtil) { var a = { printDate: function() { console.log(aUtil.aGetFormatDate(date)) } } return a })
//main.js require(['./a.js'], function(a) { var date = new Date() a.printDate(date) })
<script data-main="./main.js" src="./require.js"/>
-
AMD("Asynchronous Module Definition"的缩写) 和 CommonJS 的使用场景
- 需要异步加载 JS,使用 AMD
- 使用了 npm 后建议使用 CommonJS
webpack 的使用
//初始化文件
npm init
//安装webpack
npm install webpack --save-dev
//webpack.config.js
var path = require('path')
var webpack = require('webpack')
module.exports = {
context:path.resolve(__dirname,'./src')
entry:{ //入口
app:'./app.js'
}
output:{ //出口
path:path.resolve(__dirname,'./dist')
filename:'./bundle.js'
}
}