用于对模块的源代码进行转换,在import或load模块时预处理文件。
使用loader
module.exports = {module: {rules: [{test: /\.css$/,use: [{loader: 'style-loader'},{loader: 'css-loader',options: {modules: true}},{loader: 'sass-loader'}]},{ test: /\.ts$/, use: 'ts-loader' },],},}
loader从右至左(或从下至上)的取值执行,上例中css处理会先调用sass-loader,再调用css-loader,最后调用style-loader。
也可使用内联loader import css from 'style-loader!css-loader?modules!./style.css',不推荐
特性
- 支持链式调用
- 可以是同步或异步
- 运行在nodejs中
- 支持options配置
- plugins可扩展loader
- 可生成其它任意文件
编写loader
loader为一个node module且输出一个函数,该函数可通过 this上下文 使用 Loader API。
官方例子
利用其它模块提供的方法如loader-utils、schema-utils
import { urlToRequest } from 'loader-utils';import { validate } from 'schema-utils';const schema = {type: 'object',properties: {test: {type: 'string',},},};export default function (source) {const options = this.getOptions();validate(schema, options, {name: 'Example Loader',baseDataPath: 'options',});console.log('The request path', urlToRequest(this.resourcePath));// Apply some transformations to the source...return `export default ${JSON.stringify(source)}`;}
使用外部依赖
import path from 'path';export default function (source) {var callback = this.async();var headerPath = path.resolve('header.js');this.addDependency(headerPath);fs.readFile(headerPath, 'utf-8', function (err, header) {if (err) return callback(err);callback(null, header + '\n' + source);});}
处理模块依赖
对于css,再loader处理其中@import和url(...)时可使用以下两个方法:
- 替换为
require语句 - 使用
this.resolve方法转换
如css-loader使用require替换,而在less中则使用this.resolve。
常用loader
- style-loader:将css文件通过
style标签添加到html中 - css-loader:分析css模块之间的关系,并合并成一个文件
- less-loader:编译less为css
- file-loader:将指定的资源文件转存到指定输出目录,返回目录地址
