webpack 學習筆記:核心概念(上)

zhangbao發表於2020-09-26

想能順暢使用 webpack 開發,前提就要明白其中牽涉到一些核心概念。先從全域性角度,俯瞰大概,之後再深入細節,方能遊刃有餘。

webpack 中會涉及到如下幾個核心概念:

Entry

Entry 即 Entry point,即打包入口。從入口出發,發現依賴,以及依賴的依賴……直至所有依賴關係統計、分析完畢,最終會織成一張依賴網(dependency graph),確保能準確無誤的打包專案。

Entry 可通過配置檔案的 entry 選項指定,預設為 ./src/index.js

// webpack.config.js
module.exports = {
    entry: './path/to/my/entry/file.js'
};

Output

有入口,就有出口。output 選項就是用來指定,專案打包後的目標地址的。

// webpack.config.js
const path = require('path');

module.exports = {
    entry: './path/to/my/entry/file.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'my-first-webpack.bundle.js'
    }
};

上面指定打包後目標地址是 dist/my-first-webpack.bundle.js。

Loaders

webpack 預設只能解析 JavaScript 和 JSON 檔案。如果想能正確處理其他檔案型別,就需要使用 Loader 做轉換,將檔案轉換成 webpack 認識的有效 module。

// path/to/my/entry/file.js
const pkg = require('../../../../package.json')

function say(what = 'Hello webpack') {
    return `?(v${pkg.version}) ${what}`
}

document.body.appendChild(
    document.createElement('h1').appendChild(document.createTextNode(say()))
)

這個檔案能被成功打包。

webpack 學習筆記:核心概念

如果是引入 .txt 文字,打包就會出錯。

// path/to/my/entry/file.js
const pkg = require('../../../../package.json')
const p = require('./test.txt')

function say(what = 'Hello webpack') {
    return `?(v${pkg.version}) ${what}`
}

document.body.innerHTML = `
    <h1>${say()}</h1>
    <p>${p}</p>
`
$ npx webpack

Hash: b42def63aa2778722737
Version: webpack 4.44.2
Time: 198ms
Built at: 2020-09-26 10:14:07 ├F10: AM┤
 1 asset
Entrypoint main = my-first-webpack.bundle.js
[0] ./path/to/my/entry/file.js 392 bytes {0} [built]
[1] ../package.json 310 bytes {0} [built]
[2] ./path/to/my/entry/test.txt 464 bytes {0} [built] [failed] [1 error]

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

ERROR in ./path/to/my/entry/test.txt 1:4
Module parse failed: Unexpected token (1:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> Out of the box, webpack only understands JavaScript and JSON files. Loaders allow webpack to process other types of files and convert them into valid modules that can be consumed by your application and added to the dependency graph.
 @ ./path/to/my/entry/file.js 2:10-31

安裝 raw-loader,新增對 .txt 檔案的解析支援。

$ npm install raw-loader --save-dev
// webpack.config.js
const path = require('path');

module.exports = {
    entry: './path/to/my/entry/file.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'my-first-webpack.bundle.js'
    },
    module: {
        rules: [
            // See: https://webpack.js.org/loaders/raw-loader/
            { test: /\.txt$/, use: { loader: 'raw-loader', options: { esModule: false } } }
        ]
    }
};

loaders 配置項有兩個:

  • test: 匹配需要轉換的檔案
  • use: 使用哪個 loader。值可以是字串,也可以是物件

然後再次打包就沒問題了。

webpack 學習筆記:核心概念

(完)

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章