1. 程式人生 > >Webpack入門第一節

Webpack入門第一節

1.使用Webpack前需要做的準備

在新專案資料夾中新建立package.json,這是一個標準的npm說明檔案,裡面蘊含了豐富的資訊,包括當前專案的依賴模組,自定義的指令碼任務。(在終端可以使用npm init可以自動建立package.json)檔案。

輸入這個命令後,終端會問你一系列諸如專案名稱,專案描述,作者等資訊,不過不用擔心,如果你不準備在npm中釋出你的模組,這些問題的答案都不重要,回車預設即可。

對應生成的package.json檔案

{
  "name": "pack",
  "version": "1.0.0",
  "description": "",
  "main": "app/main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "gx",
  "license": "ISC"
}

2.安裝webpack

(1)在本專案中安裝webpack作為依賴包。

npm install --save-dev webpack

(2)全域性安裝

npm install -g webpack

這裡我選用的是在專案中安裝即第一種方法。

回到專案根目錄建立兩個資料夾,app和public,app資料夾用來存放原始資料和我們將寫的javaScript模組,public資料夾用來存放之後供瀏覽器讀取的檔案,

(包括使用webpack打包生成的js檔案以及一個index.html檔案)。接下來我們再建立三個檔案:

index.html --放在public資料夾中;

Greeter.js

-- 放在app資料夾中;

main.js-- 放在app資料夾中;

專案結構如圖所示:

index.html中檔案內容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Webpack Sample Project</title>
</head>
<body>
<div id='root'>
</div>
<script src="bundle.js"></script>
</body>
</html>

 我們在Greeter.js中定義一個返回包含問候資訊的html元素的函式,並依據CommonJS規範匯出這個函式為一個模組:

// Greeter.js
module.exports = function() {
  var greet = document.createElement('div');
  greet.textContent = "Hi there and greetings!";
  return greet;
};

main.js檔案中我們寫入下述程式碼,用以把Greeter模組返回的節點插入頁面。

//main.js 
const greeter = require('./Greeter.js');
document.querySelector("#root").appendChild(greeter());

使用webpack命令打包,基本使用方法如下:

webpack {entry file} {destination for bundled file}

 指定入口檔案後,webpack將自動識別專案所依賴的其它檔案,不過需要注意的是如果你的webpack不是全域性安裝的,那麼當你在終端中使用此命令時,需要額外指定其在node_modules中的地址,繼續上面的例子,在終端中輸入如下命令

node_modules\.bin\webpack app\main.js --output public\bundle.js

命令用的不對,應該加上--output表明public\bundle.js輸出檔案。

開啟index.html頁面我們可以看到,在Greeter.js中輸入的內容Hi there and greetings!

此時我們已經成功的使用Webpack打包了一個檔案了。