创建自己的Loader
module.exports = function (content) {console.log('async------------------')return content}
引入loader
resolveLoader属性
resolveLoader: {modules: ['./wsy-loader', "node_modules"],},
const path = require('path');const htmlWebpackPlugin = require('html-webpack-plugin');const { CleanWebpackPlugin }= require('clean-webpack-plugin');module.exports = {entry: './src/main.js',mode: 'production',output: {path: path.resolve(__dirname, 'dist'),filename: 'main.js',},resolveLoader: {modules: ['./wsy-loader', "node_modules"],},module: {rules: [{test: /\.js$/,use: [{loader: 'wsy-loader1'}],enforce: 'pre'}, {test: /\.js$/,use: [{loader: 'wsy-loader-async',}, ]}],},plugins: [new htmlWebpackPlugin({template: path.resolve(__dirname, 'public/index.html'),title: 'test-loader'}),new CleanWebpackPlugin()]};
loader的执行顺序
从后向前、从右向左的
async------------------norm--------------------------
pitch-loader
norm---------pitch-----------------async---------pitch-----------------async------------------norm--------------------------
enforce
enforce一共有四种方式:
- 默认所有的loader都是normal;
- 在行内设置的loader是inline(在前面将css加载时讲过,import ‘loader1!loader2!./test.js’);
- 也可以通过enforce设置 pre 和 post;
module: {rules: [{test: /\.js$/,use: [{loader: 'wsy-loader1'}],enforce: 'pre'},{test: /\.js$/,use: [{loader: 'wsy-loader-async',}, ]}],},
在Pitching和Normal它们的执行顺序分别是:
- post, inline, normal, pre;
- pre, normal, inline, post;
async---------pitch-----------------norm---------pitch-----------------norm--------------------------async------------------
同步的Loader
默认创建的Loader就是同步的Loader,
这个Loader必须通过 return 或者 this.callback 来返回结果,交给下一个loader来处理;
p通常在有错误的情况下,我们会使用 this.callback;
this.callback的用法如下:
- 第一个参数必须是 Error 或者 null;
- 第二个参数是一个 string或者Buffer;
// 第一种module.exports = function (content) {return content}// 第二种module.exports = function (content) {this.callback(null,content)}
异步的Loader
module.exports = function (content) {const callback = this.async()setTimeout(()=>{callback(null,content)})}
传入和获取参数
- this.query
- loader-utils
// 第一种const {getOptions} = require('loader-utils');module.exports = function (content) {const options = getOptions(this);console.log('norm--------------------------', options)return content}// 第二种module.exports = function (content) {const options = this.query;console.log('norm--------------------------', options)return content}
校验参数
安装依赖
yarn add schema-utils -D
// 新建schema.json{"type": "object","properties": {"name": {"type": "string","description": "请选择true or false"},"sourceMap": {"type": "boolean","description": "sourceMap值是不对的啊"}},"additionalProperties": true}
const {getOptions} = require('loader-utils');const schemaOptions = require("./schema.json")const configuration = {name: "Loader Name/Plugin Name/Name"};const {validate} = require('schema-utils');module.exports = function (content) {const options = getOptions(this);validate(schemaOptions, options, {name: "MyPlugin",postFormatter: (formattedError, error) => {return formattedError;},})this.callback(null, content)}
