js模块化 - CommandJS

1.模块化入门

1.1 什么是模块化
  • 将一个复杂的成像依据一定规则拆分成单个文件,最终组合在一起
  • 这些拆分的文件就是模块,模块内部数据是私有的,只是向外部暴露一些方法与外部其他模块通信
1.2 为什么要模块化
  • 降低复杂度,提高解耦性
  • 避免命名冲突
  • 更好的分离,按需加载
  • 更高复用性,高维护性
1.3 模块化带来的问题
  • 请求过多
  • 依赖模糊 (合)
  • 难以维护

先拆再合

2. 模块化规范

一个大的项目必定会使用模块化技术,使用模块化就会使用相应的模块化规范
现在比较流行的模块化规范有两种:CommonJS、 ES6

2.1 CommonJS(双端)
2.2.1 规范
  • 官网: http://wiki.commonjs.org/wiki/modules
  • 每个文件都是一个模块
  • CommonJS 模块化的代码既可以在服务端运行,也可以在浏览器端运行
  • 服务器端:模块化代码可以直接运行
  • 浏览器端:模块化的代码要经过 Browserify( http://browserify.org) 编译。
2.1.2 基本语法
  • export 模块暴露数据
    第一种方式:module.exports = value
    第二种方式:module.xxx = value
  • import引入模块
    引入第三方模块;require(模块名)
    引入自定义模块:require(模块文件路径)
  • 内置关系


    d99367c63795478b86b7489ee407aff5.png
  • 同时暴露多个

第一种方式

# module1 使用module.exports=xxx暴露
# module.exports 和exports不能混用,若混用了,以 module.exports为主
const data='athui'
const msg='hello'
module.exports={
    showData(){
        console.log(data);
    },
    showMsg(){
        console.log(msg);
    }
}
exports.x=100// 不起效

第二种方式

exports.sum = function(a,b){
    console.log(a+b);
}
exports.sub = function(a,b){
    console.log(a-b);
}
export.a=1

在app.js中引入

# 引入的内容是什么,取决的暴露的是什么
const {showData,showMsg} = require('./module1') //引入自定义模块
const {sum,sub,a} = require('./module2')
const uniq = require('uniq') //引入第三方包
const arr= [1,2,10,5]
console.log(uniq()arr); //去重 字典排序1 10 2 5

【node环境下运行】node app.js
【浏览器环境下运行】执行

index.html
全局安装browserify npm i browserify -g
编译指定文件 browerserify ./app.js -o ./build.js
在html页面种引入build.js


c9a5254c57eb4ea0a21e7577f841b08f.png

在index.html中引入
<script type="text/javascript" src=".bulid.js"></script>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。