1. 程式人生 > 實用技巧 >Webpack 入門 基礎知識

Webpack 入門 基礎知識

寫一個Render物件可以在#root元素下掛載字串的物件,使用ES Module語法匯入後通過Webpack打包

Step 0. 建立npm專案 hello-webpack

  • mkdir hello-webpack && cd hello-webpack

  • mkdir src && mkdir dist 建立原始碼目錄

  • npm init demo專案一路預設即可

  • 安裝webpack/webpack-cli npm install webpack webpack-cli --save-dev

Step 1. 專案根路徑建立index.html

這是作為專案對外展示的主頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="root"></div>
    <script src="./dist/bundle.js"></script>
</body>
</html>

./dist/bundle.js還不存在,稍後webpack會自動打包出來,這裡先匯入

Step 2. 編寫src/render.js和src/index.js

src/render.js

class Render {
    message(mountPoint, text) {
        var message = document.createElement("div")
        message.innerText = text
        mountPoint.append(message)
    }
}

export default Render;

src/index.js

import Render from './render'


new Render().message(document.getElementById("root"), "Hello, World!")

Setp 3. 編寫webpack配置檔案webpack.config.js

const path = require("path")

var config = {
    mode: 'development',
    entry: {
        main: './src/index.js'
    },
    output: {
        filename: "bundle.js",
        path: path.resolve(__dirname, "dist")
    }
}

module.exports = config

Step 4. 建立Npm Script

package.json中的scripts物件新增一欄build命令

{
  "name": "hello-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --config ./webpack.config.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^5.4.0",
    "webpack-cli": "^4.2.0"
  }
}

在專案根路徑下執行命令npm run build,開始打包,完成

頁面成功顯示Hello, World!