🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## AMD [require.js官网](http://requirejs.org/) 引入 require.js 会产生一下几个全局 - 全局 define函数 - 全局 require函数 - 依赖js会自动、异步加载 ## 使用非 AMD 形式的 模块化 ``` //util.js export{ getFormatDate:function(date,type){ } } //a-util.js var getFormatDate = require('util.js') export{ aGetormatDate:function(date){ return getFormatDate(date,2) } } //a.js var aGetormatDate = require('a-util.js') var dt = new Date() console.log(aGetormatDate(dt)) //HTML 中 引入 a 文件 即可 不会带来全局污染 <script scr='a.js '>< /script> ``` ### 使用require.js 进行模块化 依赖中的文件会异步加载 ``` //util.js define(function(){ return { getFormatDate;function(date,type){ if (type===1) { return '2017-06-15' }else if(type===2){ return '2017年6月15日' } } } }) //a-util.js define(['./util.js'],function(util){ return { aGetFormatDate:function(date){ return util.getFormatDate(date,2) } } }) //a.js define(['./a-util.js'],function(aUtil){ return { printDate:function(date){ console.log(aUtil.aGetFormatDate(date)) } } }) //main.js require(['./a.js'],function(a){ var date = new date() a.printDate(date) }) //HTML 中 引入 a 文件 即可 不会带来全局污染 <script src="/require.min.js" data-main="./main.js"></script> //require.js 也可以使用 CDN 上的 js ``` ### CommonJs 实现模块化 - nodes模块化规范,现在被大量用前端,原因 - 前端开发依赖的插件和库,都可以从npm中获取 - 构建工具的高度自动化,使得使用npm的成本非常低 - Commons不会异步加载JS,而是同步一次性加载出来 ### AMD和 Commons的使用场景 - 需要异步加载JS,使用AMD - 使用了npm之后建议使用 Commons ## 构建工具 - grunt - gulp - fis4 ### webpack 准备工作 1. 安装 nodejs 2. 安装`http-server` `sudo npm install http-server -g` #### 搭建 webpack 环境 1. 初始化 npm `npm init ` 填写相关项目相关信息 2. 安装 webpack ``` npm install webpack --save-dev --save : 保存起来 -dev : 只用在开发环境 ``` 3. 安装 `jquery` `npm install jquery --save` 4. 在项目目录中创建`webpack.config.js` ```js var path = require('path') var webpack = require ('webpack') module.exports = { context:path.resolve(__dirname,'./src'), //资源路径 entry:{ app:'./app.js' //app 的入口文件 }, output:{ path:path.resolve(__dirname,'./dist'), //输出文件地方 filename:'bundle.js' } } ``` 在`src/app.js`添加 `console.log(100)` 在 `packpage.json` 添加新的的script ``` "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack" //添加 webpack 在命令行中 运行 npm start }, ``` 在命令行中 `npm start` #### webpack 引用 jquery 在上诉项目中`app.js`引入 juqery ```js var $ = require('jquery') console.log($("body")); ``` 重新构建 `npm start` 刷新页面即可 #### 引入 a-utils.js 在`src/a-utils.js`中 ``` module.exports = { print:function(){ console.log(123) } } ``` 在`src/app,js` 中 ``` var aUtil = require('./a-utils.js') aUtil.print() ``` //重构 `npm start` 重构 `npm start`