通過小例子一步步掌握webpack基本用法

首先熟悉幾個概念: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中引入該打包文件。

三、未完待續。。。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 無意中看到zhangwnag大佬分享的webpack教程感覺受益匪淺,特此分享以備自己日后查看,也希望更多的人看到...
    小小字符閱讀 8,240評論 7 35
  • publicPath指定了一個在瀏覽器中被引用的URL地址。 對于使用 和 加載器,當文件路徑不同于他們的本地磁盤...
    飛呀飛哥閱讀 1,725評論 0 0
  • webpack 介紹 webpack 是什么 為什么引入新的打包工具 webpack 核心思想 webpack 安...
    yxsGert閱讀 6,515評論 2 71
  • 隨著前端業務復雜度的增加,模塊化成為一個大的趨勢。而在ES6還未被瀏覽器所支持的情況下,commonjs作為ES6...
    吳高亮閱讀 1,064評論 0 3
  • 1 手機傳來“嘀嘀”聲時,良一腦子里也全是這“滴滴”聲。他睜開眼睛拿起手機看了眼發消息的人,又將手機放下。他望著空...
    子俊欸閱讀 531評論 2 2