Hshen
人若无名 便可潜心练剑
GitHub Abou byHshen Hshen

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.dataloader有两个阶段const data = this.data
this.cacheable设置当前loader是否可以被缓存默认缓存this.cacheable(true)
this.async异步回调 loader。返回 this.callbackconst callback = this.async()
this.callback返回loader的处理结果this.callback(err, content)
this.getOptions(schema)获取 loader 的 optionsthis.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)

官方 Loader Interface

参考

raw-loader