js模块化规范—commonjs

commonjs规范说明

每个js文件都可当作一个模块

在服务器端: 模块的加载是运行时同步加载的(不会阻塞,等待时间回比较长)。在浏览器端: 模块需要提前编译打包处理

commonjs规范基本语法

暴露模块:暴露的模块本质上就是exports,exports本来就是一个空的对象,将value赋给它

module.exports = value

exports.xxx = value

引入模块:第三方模块:xxx为模块名。自定义模块: xxx为模块文件路径

require(xxx)

commonjs基于服务器端(node)应用

/**
 * 使用module.exports = value向外暴露一个对象
 */
"use strict"
module.exports = {
  foo() {
    console.log('moudle1 foo()')
  }
}
/**
 * 使用module.exports = value向外暴露一个函数
 */
"use strict"
module.exports = function () {
  console.log('module2()')
}
/**
 * 使用exports.xxx = value向外暴露一个对象
 */
"use strict"
exports.foo = function () {
  console.log('module3 foo()')
}

exports.bar = function () {
  console.log('module3 bar()')
}
"use strict"
//引用模块
let module1 = require('./modules/module1')
let module2 = require('./modules/module2')
let module3 = require('./modules/module3')
let uniq = require('uniq') // 安装的一个npm包
let fs = require('fs')

//使用模块
module1.foo()
module2()
module3.foo()
module3.bar()

console.log(uniq([1, 3, 1, 4, 3]))

fs.readFile('app.js', function (error, data) {
  console.log(data.toString())
})

 

commonjs基于浏览器端应用

创建项目结构

|-js
  |-dist //打包生成文件的目录
  |-src //源码所在的目录
    |-module1.js
    |-module2.js
    |-module3.js
    |-app.js //应用主源文件
|-index.html
|-package.json
  {
    "name": "browserify-test",
    "version": "1.0.0"
  }

下载browserify

Browserify:也称为CommonJS的浏览器端的打包工具

全局: npm install browserify -g,局部: npm install browserify --save-dev

定义模块1

/**
 * 使用module.exports = value向外暴露一个对象
 */
module.exports = {
  foo() {
    console.log('moudle1 foo()')
  }
}

定义模块2

/**
 * 使用module.exports = value向外暴露一个函数
 */
module.exports = function () {
  console.log('module2()')
}

定义模块3

/**
 * 使用exports.xxx = value向外暴露一个对象
 */
exports.foo = function () {
  console.log('module3 foo()')
}

exports.bar = function () {
  console.log('module3 bar()')
}

app.js (应用的主js)

//引用模块
let module1 = require('./module1')
let module2 = require('./module2')
let module3 = require('./module3')

let uniq = require('uniq')

//使用模块
module1.foo()
module2()
module3.foo()
module3.bar()

console.log(uniq([1, 3, 1, 4, 3]))

打包处理js

browserify js/src/app.js -o js/dist/bundle.js

页面使用引入

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--<script type="text/javascript" src="js/src/app.js"></script>-->
    <script type="text/javascript" src="js/dist/bundle.js"></script>
</body>
</html>
原文地址:https://www.cnblogs.com/LO-ME/p/10652436.html