webpack loader

A loader is just a JavaScript module that exports a function
loader 用于对模块的源代码进行转换。

官方文档

在官方文档中,loader 被看做在打包过程中的中间件,对不同文件进行转换处理。

loader 特性得出:

  • 支持链式传递。
    这个有点像 gulp 的文件流 .pipe 。通过在 loader 中传递加以处理的资源,最后一个 loader 返回处理预期的代码。会以相反顺序执行。
  • 可同步可异步。
    调用 this.async() 实现。
  • 运行在 nodejs 中。
    则符合 CMD 规范。写法如:module.exports & require
  • 接收查询参数。
    通过 this.query 获取查询参数。如:css?sourcemap
  • 能够使用 options 对象进行配置。
    旧版本写法是 query ,新版本写法是 options。通过 this.query 获取。
  • plugin 可以为 loader 带来更多属性。
  • loader 能够产生额外的任意文件。

编写 loader

loader 是导出为一个函数的 node 模块。该函数在 loader 转换资源时调用。给定的函数将调用 loader api,并通过 this 上下文访问。

  • 设置本地文件位置。
// 单个 loader
{
  test: /\.js$/
  use: [
    {
      loader: path.resolve('path/to/loader.js'),
      options: {/* ... */}
    }
  ]
}
// 多个 loaders。
resolveLoader: {
  modules: [
    'node_modules',
    path.resolve(__dirname, 'loaders')
  ]
}
  • 基本写法。
module.exports = function (source) {
    // 使用缓存
    this.cacheable()

    // 异步
    let callback = this.async()
    // 输出文件
    this.emitFile(name: string, content: Buffer | string, sourceMap: (...))

    this.callback(null | err, source)
}
import loaderUtils from 'loader-utils'

module.exports = function (source) {

    // 获取 options
    loaderUtils.getOptions(this)

    // 绝对路径转相对路径
    loaderUtils.

    // 其余用法
    ...
}

results matching ""

    No results matching ""