commonjs規範說明javascript
每一個js文件均可看成一個模塊html
在服務器端: 模塊的加載是運行時同步加載的(不會阻塞,等待時間回比較長)。在瀏覽器端: 模塊須要提早編譯打包處理java
commonjs規範基本語法node
暴露模塊:暴露的模塊本質上就是exports,exports原本就是一個空的對象,將value賦給它npm
module.exports = value
exports.xxx = value
引入模塊:第三方模塊:xxx爲模塊名。自定義模塊: xxx爲模塊文件路徑json
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基於瀏覽器端應用服務器
建立項目結構app
|-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>