webpack loader
2022年4月9日
预计阅读:2min
实现一个最简单的loader
导入txt文件并输出;
txt-loader.js
// loader是一个JS模块,导出内容为一个函数
module.exports = function (source) {
// 因为我们是import导入的文件 所以模块导出的内容
// 需要是一个字符串 且格式为ESM或commonJS;
return `export default ${JSON.stringify(source)}`;
}
index.js
// 导入txt文件
import txt from "./text.txt";
console.log(txt);
text.txt
Hello
使用loader-runner进行调试
const runLoaders = require('runLoaders');
const fs = require('fs')
const path = require('path');
runLoaders({
// 导入资源的绝对路径
resource: path.resolve(__dirname, './index.js'),
loaders: [
path.resolve(__dirname, './txt-loader.js')
],
// loader执行上下文
context: {minimize: true},
readResource: fs.readFile.bind(fs)
}, function (err, result) {
if (err) return;
console.log(result)
})
loader 中常用api
方法名 | 含义 | 用法 |
---|---|---|
this.context | 被处理文件所在路径 | const context = this.context |
this.data | loader有两个阶段 | const data = this.data |
this.cacheable | 设置当前loader是否可以被缓存默认缓存 | this.cacheable(true) |
this.async | 异步回调 loader。返回 this.callback | const callback = this.async() |
this.callback | 返回loader的处理结果 | this.callback(err, content) |
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) |