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基于浏览器端应用

猜你喜欢

转载自www.cnblogs.com/LO-ME/p/10652436.html