用于对模块的源代码进行转换,在import或load模块时预处理文件。

使用loader

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. use: [
  7. {loader: 'style-loader'},
  8. {
  9. loader: 'css-loader',
  10. options: {
  11. modules: true
  12. }
  13. },
  14. {loader: 'sass-loader'}
  15. ]
  16. },
  17. { test: /\.ts$/, use: 'ts-loader' },
  18. ],
  19. },
  20. }

loader从右至左(或从下至上)的取值执行,上例中css处理会先调用sass-loader,再调用css-loader,最后调用style-loader。
也可使用内联loader import css from 'style-loader!css-loader?modules!./style.css',不推荐

特性

  1. 支持链式调用
  2. 可以是同步或异步
  3. 运行在nodejs中
  4. 支持options配置
  5. plugins可扩展loader
  6. 可生成其它任意文件

    编写loader

    loader为一个node module且输出一个函数,该函数可通过 this上下文 使用 Loader API。

官方例子

利用其它模块提供的方法如loader-utils、schema-utils

  1. import { urlToRequest } from 'loader-utils';
  2. import { validate } from 'schema-utils';
  3. const schema = {
  4. type: 'object',
  5. properties: {
  6. test: {
  7. type: 'string',
  8. },
  9. },
  10. };
  11. export default function (source) {
  12. const options = this.getOptions();
  13. validate(schema, options, {
  14. name: 'Example Loader',
  15. baseDataPath: 'options',
  16. });
  17. console.log('The request path', urlToRequest(this.resourcePath));
  18. // Apply some transformations to the source...
  19. return `export default ${JSON.stringify(source)}`;
  20. }

使用外部依赖
  1. import path from 'path';
  2. export default function (source) {
  3. var callback = this.async();
  4. var headerPath = path.resolve('header.js');
  5. this.addDependency(headerPath);
  6. fs.readFile(headerPath, 'utf-8', function (err, header) {
  7. if (err) return callback(err);
  8. callback(null, header + '\n' + source);
  9. });
  10. }

处理模块依赖

对于css,再loader处理其中@importurl(...)时可使用以下两个方法:

  • 替换为require语句
  • 使用this.resolve方法转换

css-loader使用require替换,而在less中则使用this.resolve。

常用loader

  • style-loader:将css文件通过style标签添加到html中
  • css-loader:分析css模块之间的关系,并合并成一个文件
  • less-loader:编译less为css
  • file-loader:将指定的资源文件转存到指定输出目录,返回目录地址