# loader是什么

简单而言就是模块转换器, 因为webpack只能识别js模块, 例如对css/img等资源处理, 就需要相对应的loader转换成js模块, 才可以做进一步处理

# 自定义loader

# 返回值格式:

this.callback(
  err: Error | null, // Error 或者 null
  content: string | Buffer, // string 或者 Buffer
  sourceMap?: SourceMap,
  meta?: any // 元数据
);
1
2
3
4
5
6

# 同步loader返回值


// 同步loader 只返回一个处理结果
module.exports = function(content, map, meta) {
  return someSyncOperation(content);
};

// 同步loader 返回多个处理结果
module.exports = function(content, map, meta) {
  this.callback(null, someSyncOperation(content), map, meta);
};

1
2
3
4
5
6
7
8
9
10
11

# 异步loader返回值

异步模式下使用 this.async 来获取 callback 函数

module.exports = function(content, map, meta) {
  var callback = this.async();
  someAsyncOperation(content, function(err, result, sourceMaps, meta) {
    if (err) return callback(err);
    callback(null, result, sourceMaps, meta);
  });
};
1
2
3
4
5
6
7

# 编写loader:

import { getOptions } from 'loader-utils';
export default async function myLoader (source) {
  // 异步模式
  let callback = this.async()
  // 获取 options
  const options = loaderUtils.getOptions(this) || {}
  try {
    let result;
    // 处理source
    callback(null, result)
  } catch (err) {
    callback(err)
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 使用自定义loader

// webpack.config.js
module.exports = {
  // 其他配置...
  module: {
    rules: [{
      test: /\.js$/,
      use: [{
        loader: 'myLoader',
        options: {
          name: "richard" 
        }
      }]
    }]
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
上次更新: 2020-02-28 02:55:43