首先熟悉幾個概念:CommonJs規范、AMD規范、CMD規范,CommonJs規范指使用require("文件名")來加載,使用module.exports 暴露借口,一個文件相當于一個模塊,有著單獨的作用域。
AMD規范使用如下方式來加載文件:
// index.js
define(["./a","./b"],function(){
function init(){
console.log(1);
}
return {
init:init
}
});
require(["./index"],function(index){ // 依賴必須一開始就寫好
index.init();
}) //1
CMD 規范兼容了CommonJs 規范和AMD規范,實例如下:
define(function(require, exports, module){
var a = require("./a.js");
a.dosomething;
require("./b.js"); //依賴可以就近書寫
b.dosomething;
// 通過 exports 對外提供接口
// exports.doSomething = ...
// 或者通過 module.exports 提供整個接口
module.exports = ...
});
一、簡單理解打包
在項目目錄下執行webpack命令,如果該目錄下存在webpack.config.js則執行該文件下的配置,eg:
module.exports = {
entry: 'index.js',
output: {
filename:'index.bundle.js'
}
}
如果沒有則需要手動輸入webpack的配置命令,eg:
webpack index.js index.bundle.js
以上兩種方式都可以將指定文件進行打包打包。
二、處理模塊依賴
我們比較熟悉使用<script>的先后引用來處理模塊的依賴關系,如下:
// index.html
<!DOCTYPE html>
<html>
<head>
<title>演示模塊相互依賴</title>
<meta charset="utf-8" />
<script type="text/javascript" src="./a.js"></script>
<script type="text/javascript" src="./b.js"></script>
</head>
</html>
其中b.js依賴a.js,先引用a.js再引用b.js,其中a.js代碼如下:
// a.js
function a(){
console.log('hello webpack');
}
b.js 代碼如下:
//b.js
a();
以上例子比較好理解,接下來我們演示如何使用webpack處理以上依賴,只需將以上代碼改為:
// index.html
<!DOCTYPE html>
<html>
<head>
<title>演示模塊相互依賴</title>
<meta charset="utf-8" />
<script type="text/javascript" src="bundle.js"></script>
</head>
</html>
// a.js
function a(){
console.log('hello webpack');
}
module.exports = a; // CommonJs規范暴露
/*
// AMD規范暴露
define(function(){
function init(){
console.log('hello webpack');
}
return {
init: init
}
})
*/
// b.js
var a = require('./a.js'); // 使用CommonJs方式進行加載
/*
// 使用AMD方式進行加載
require(["a"],function(a){
a.init();
})
*/
a();
執行 webpack b.js bundle.js,并在index.html中引入該打包文件。