Webpack Loaders 进阶

什么是 Loaders

Loaders 可以认为是 import 或 “load” 模块时的预处理工具。它可以对导入的不同类型的模块(css,ts,png)进行转化,成为 javascript 代码

核心原理

一个 loader 是一个 node module,导出一个方法,该方法接收一个参数(导入模块的内容,stream 或 string),返回一个经过转换的新字符串(或 stream),这就是 loader 的工作原理

1
2
3
4
// simplest loader
module.exports = function(source) {
return source
}

Loaders 主要特性

  • 支持级连,从右向左处理,每个 loader 都返回处理完成的代码给下一个 loader
1
use: ['style-loader', 'css-loader']
  • loaders 可以是异步也可以是同步

  • loaders 可以输出任意文件(emit files)
    如 file-loader

  • loaders 可以接受参数,主要有两种方式传入参数

1
2
3
4
5
6
7
8
9
10
11
// 1. query string
use: 'file-loader?name=images/[hash].[ext]'

// 2. options
use: {
loader: 'file-loader',
options: {
name: '[hash].[ext]',
outputPath: 'images/'
}
}

在 loaders 中接受参数:

1
2
3
4
5
6
const loaderUtils = require('loader-utils')

module.exports = function(source) {
const options = loaderUtils.getOptions(this)
return source
}

注意,上面的 options 值主要有几种情况:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 1. passing config using query string like
use: 'file-loader?name=images/[hash].[ext]'
// options equals to the query Object

// 2. passing config using options like
use: {
loader: 'file-loader',
options: {
name: images/[hash].[ext]
}
}
// options equals to the options object

// 3. passing config using both query and options
use: {
loader: 'file-loader?name=images/[hash].[ext]',
options: {
name: images/[hash].[ext]
}
}
// options equals to the options object

如何写一个 loader ?

我写了一个 demo,展示 loaders 是怎么工作的,包含如何调试 loaders