webpack中loader的执行顺序是从右到左执行的,因为webpack 内部采用的函数组合是 compose 这种形式,compose 函数式组合的特点就是 从右到左执行。
函数组合是函数式编程的重要思想,分为 pipe 和 compose 两种形式。
pipe 采用的是 从左到右的 形式。
compose 采用的是 从右到左的形式。
// 实现 compose 函数// compose 函数的特点是接受若干个函数参数,其中的每一个参数函数都只接受一个参数,// compose 函数返回一个函数,这个返回函数也只接受一个参数function compose(...funcs) {return x => {let length = funcs.length;if (!length) return x;if (length === 1) return funcs[0](x);/*** 第一次:preValue 接受的是 x 为 0 curValue 接受的是 add1 add1(0):1* 第二次:preValue 接受的是 x 为 1 curValue 接受的是 add1 add1(1):2* 第三次:preValue 接受的是 x 为 2 curValue 接受的是 mul3 mul3(1):6* 第三次:preValue 接受的是 x 为 6 curValue 接受的是 div2 div2(6):3*/return funcs.reduceRight((preValue, curValue) => curValue(preValue), x);}}// testconst add1 = (x) => x + 1;const mul3 = (x) => x * 3;const div2 = (x) => x / 2;const operate = compose(div2, mul3, add1, add1)console.log(operate(0));
