webpack 介紹

何謂Webpack?

  • Webpack 是一套Javascript模組打包工具(is a module bundler for your JavaScript.)
  • 後來由於越來越多人使用後,變成為Javascript的管理工具(壓縮、合併等工作)。
  • 工作流程:
    webpack工作流程

安裝 Webpack

npm install -g webpack

// 使用 Yarn
yarn global add [email protected] [email protected]
yarn add --dev [email protected] [email protected]

webpack.config.js 設定檔

'use strict';

const webpack = require("webpack");

module.exports = {
  context: __dirname + "/src",
  entry: {
    app: "./app.js",
  },
  output: {
    path: __dirname + "/dist",
    filename: "[name].bundle.js",
  },
};

// __dirname refers to the root of your project.

Webpack 會做的事情

  • Starting from the context folder, …
  • it looks for entry filenames
  • and reads the content. Every import (ES6) or require() (Node) dependency it finds as it parses the code
  • From there, Webpack bundles everything to the output.path folder, naming it using the output.filename naming template ([name] gets replaced with the object key from entry)

執行 Webpack

webpack -p    // p flag is “production” mode and uglifies/minifies output.

範例

  • 多個檔案變成一個檔
use strict';

const webpack = require("webpack");

module.exports = {
  context: __dirname + "/src",
  entry: {
    app: ["./home.js", "./events.js", "./vendor.js"],
  },
  output: {
    path: __dirname + "/dist",
    filename: "[name].bundle.js",
  },
};
  • 多個檔變成多個檔
const webpack = require("webpack");

module.exports = {
  context: __dirname + "/src",
  entry: {
    home: "./home.js",
    events: "./events.js",
    contact: "./contact.js",
  },
  output: {
    path: __dirname + "/dist",
    filename: "[name].bundle.js",
  },
};