模块化module/CommonJS/Browserify/AM

2019-02-09  本文已影响0人  mao77_

模块化module/CommonJS/Browserify/AMD/RequireJS/CMD/SeaJS/ES6_Babel

1. 模块化module

将一个复杂的程序依据一定的规则(规范)封装成几个块(文件), 并进行组合在一起

块的内部数据/实现是私有的, 只是向外部暴露一些接口(方法)与外部其它模块通信

1.1 全局function模式: 将不同的功能封装成不同的全局函数

1.2 namespace模式: 简单对象封装

1.3 IIFE模式: 匿名函数自调用(闭包)

1.4 IIFE模式增强 : 引入依赖

1.5 页面加载多个js的问题

2. CommonJS-Node____Node.js模块化

  1. 下载安装node.js

  2. 创建项目结构

|-modules
  |-module1.js
  |-module2.js
  |-module3.js
|-main.js
  1. 模块化编码

  1. 通过node运行index.js

3. CommonJS-BrowserifyBrowserify模块化

  1. 创建项目结构

|-build //打包生成文件的目录
|-src //源码所在的目录
  |-module1.js
  |-module2.js
  |-module3.js
  |-main.js //应用主源文件
|-index.html

  1. 下载browserify

  1. 定义模块代码

4. AMD-RequireJS

  1. 下载require.js, 并引入

  1. 创建项目结构

|-libs
  |-require.js
|-modules
  |-alerter.js
  |-dataServer.js
|-app.js
|-index.html
  1. 定义require.js的模块代码

  1. 应用主(入口): app.js

/*
  主模块:
    define()   定义没有依赖/有依赖的模块
    require()  定义异步的模块,和define用法一致
    requirejs()  定义配置,定义主模块
*/
//配置模块的路径
require.config({
  baseUrl: './',    //所有模块的公共路径
  paths: {
    dataServer: 'modules/dataServer',   // 模块名称(一定要与引入的模块名称一一对应): 模块的路径
    alerter: 'modules/alerter',    //一定不能写文件的后缀名,它会自动补全
    jquery: 'libs/jquery-1.10.1'   //库/框架自己实现模块化的功能,定义了暴露模块的名称
  }
})
//主模块
require(['jquery'], function ($) {
  $('#btn').click(function () {
    //异步加载你需要的模块,会缓存你加载的模块
    require(['alerter'], function (alerter) {
      alerter();
    })
  })
  $('body').css('background', 'deeppink');
})

console.log('1111111111111');
  1. 页面使用模块:

<script data-main="app.js" src="./libs/require.js"></script>

  1. 使用第三方基于require.js的框架(jquery)

5. CMD-SeaJS

  1. 下载sea.js, 并引入

  1. 创建项目结构

|-libs
  |-sea.js
|-modules
  |-alerter.js
  |-dataServer.js
  |-app.js
|-index.html
  1. 定义sea.js的模块代码

  1. index.html:

<!--
使用seajs:
  1. 引入sea.js库
  2. 如何定义导出模块 :
    define()
    exports
    module.exports
  3. 如何依赖模块:
    require()
  4. 如何使用模块:
    seajs.use()
-->
  <script type="text/javascript" src="./libs/sea.js"></script>
  <script type="text/javascript">
    seajs.use('./modules/app.js');
  </script>

6. ES6_Babel_Browserify

  1. 定义package.json文件

  2. 安装babel-cli, babel-preset-es2015和browserify

  1. 定义.babelrc文件

{
  "presets": ["es2015"]
}
  1. 编码

  1. 编译

  1. 页面中引入测试

<script type="text/javascript" src="lib/bundle.js"></script>
  1. 引入第三方模块(jQuery)

1). 下载jQuery模块:

* npm install jquery@1 --save

2). 在app.js中引入并使用

  import $ from 'jquery'
  $('body').css('background', 'red')
  1. 在package.json中加

    • npm run build
      "scripts": {
        "build": "babel src -d build && browserify build/app.js -o dist/bundle.js"
      },
    
上一篇 下一篇

猜你喜欢

热点阅读