导航
本章节我们主要学习:
帮助 webpack 将不同类型的文件转换为 webpack 可识别的模块。
pre > normal > inline > post 。从右到左,从下到上。例如:
// 此时loader执行顺序:loader3 - loader2 - loader1
module: {
rules: [
{
test: /\\.js$/,
loader: "loader1",
},
{
test: /\\.js$/,
loader: "loader2",
},
{
test: /\\.js$/,
loader: "loader3",
},
],
},
// 此时loader执行顺序:loader1 - loader2 - loader3
module: {
rules: [
{
enforce: "pre",
test: /\\.js$/,
loader: "loader1",
},
{
// 没有enforce就是normal
test: /\\.js$/,
loader: "loader2",
},
{
enforce: "post",
test: /\\.js$/,
loader: "loader3",
},
],
},
inline loader的前缀inline loader 可以通过添加不同前缀,跳过其他类型 loader。
! 跳过 normal loader。! 跳过 pre 和 normal loader。!! 跳过 pre、 normal 和 post loader。// loaders/loader1.js
module.exports = function loader1(content) {
console.log("hello loader");
return content;
};
它接受要处理的源码作为参数,输出转换后的 js 代码。
content 源文件的内容map SourceMap 数据meta 数据,可以是任何内容module.exports = function (content, map, meta) {
return content;
};
this.callback 方法则更灵活,因为它允许传递多个参数,而不仅仅是 content。
module.exports = function (content, map, meta) {
// 传递map,让source-map不中断
// 传递meta,让下一个loader接收到其他参数
this.callback(null, content, map, meta);
return; // 当调用 callback() 函数时,总是返回 undefined
};
module.exports = function (content, map, meta) {
const callback = this.async();
// 进行异步操作
setTimeout(() => {
callback(null, result, map, meta);
}, 1000);
};
由于同步计算过于耗时,在 Node.js 这样的单线程环境下进行此操作并不是好的方案,我们建议尽可能地使你的 loader 异步化。但如果计算量很小,同步 loader 也是可以的。
默认情况下,资源文件会被转化为 UTF-8 字符串,然后传给 loader。通过设置 raw 为 true,loader 可以接收原始的 Buffer。
module.exports = function (content) {
// content是一个Buffer数据
return content;
};
module.exports.raw = true; // 开启 Raw Loader
module.exports = function (content) {
return content;
};
module.exports.patch = function (remainingRequest, precedingRequest, data) {
console.log("do somethings");
};
webpack 会先从左到右执行 loader 链中的每个 loader 上的 pitch 方法(如果有),然后再从右到左执行 loader 链中的每个 loader 上的普通 loader 方法。

在这个过程中如果任何 pitch 有返回值,则 loader 链被阻断。webpack 会跳过后面所有的的 pitch 和 loader,直接进入上一个 loader 。

| 方法名 | 含义 | 用法 |
|---|---|---|
| this.async | 异步回调 loader。返回 this.callback | const callback = this.async() |
| this.callback | 可以同步或者异步调用的并返回多个结果的函数 | this.callback(err, content, sourceMap?, meta?) |
| this.getOptions(schema) | 获取 loader 的 options | this.getOptions(schema) |
| this.emitFile | 产生一个文件 | this.emitFile(name, content, sourceMap) |
| this.utils.contextify | 返回一个相对路径 | this.utils.contextify(context, request) |
| this.utils.absolutify | 返回一个绝对路径 | this.utils.absolutify(context, request) |
更多文档,请查阅 webpack 官方 loader api 文档
webpack 中配置 resolveLoader.module 让其除了从 node_modules 中找 loader 外,还能从我们配置的文件夹下找对应 loader 。示例如下:
const path = require('path');
module.exports = {
entry: "./src/main.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].js"
},
resolveLoader: {
modules: [
"node_modules",
path.resolve(__dirname, "loaders"),
]
},
module: {
rules: [
{
test: /\\.js$/,
exclude: /node_modules/,
use: ['custom-loader']
}
]
},
mode: "production",
}
作用:用来清理 js 代码中的console.log
// loaders/clean-log-loader.js
module.exports = function cleanLogLoader(content) {
// 将console.log替换为空
return content.replace(/console\\.log\\(.*\\);?/g, "");
};
作用:给 js 代码添加文本注释
loaders/banner-loader/index.js
const schema = require("./schema.json");
module.exports = function (content) {
// 获取loader的options,同时对options内容进行校验
// schema是options的校验规则(符合 JSON schema 规则)
const options = this.getOptions(schema);
const prefix = `
window.bannerAuthor = "${options.author}";
`;
return `${prefix} \\n ${content}`;
};
loaders/banner-loader/schema.json
{
"type": "object",
"properties": {
"author": {
"type": "string"
}
},
"additionalProperties": false
}
webpack.config.js
const path = require('path');
module.exports = {
entry: "./src/main.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].js"
},
resolveLoader: {
modules: [
"node_modules",
path.resolve(__dirname, "loaders"),
]
},
module: {
rules: [
{
test: /\\.js$/,
exclude: /node_modules/,
use: [
'clean-log-loader',
{
loader: 'banner-loader',
options: {
author: 'Lance'
}
}
]
}
]
},
mode: "production",
}
作用:编译 js 代码,将 ES6+语法编译成 ES5-语法。
npm i @babel/core @babel/preset-env -D
const schema = require("./schema.json");
const babel = require("@babel/core");
module.exports = function (content) {
const options = this.getOptions(schema);
// 使用异步loader
const callback = this.async();
// 使用babel对js代码进行编译
babel.transform(content, options, function (err, result) {
callback(err, result.code);
});
};