fe-weekly-questions icon indicating copy to clipboard operation
fe-weekly-questions copied to clipboard

loader 的执行顺序为什么是后写的先执行

Open LuckyWinty opened this issue 5 years ago • 3 comments

LuckyWinty avatar Feb 09 '20 14:02 LuckyWinty

函数组合通常有两种方式,一种是从左到右(类似 unix 的 pipe),另外一种是从右到左(compose)。此处 webpack 选择的是 compose 方式,从右到左依次执行 loader,每个 loader 是一个函数。

webpack 里面的 compose 代码为:

const compose = (...fns) => {
	return fns.reduceRight(
		(prevFn, nextFn) => {
			return value => nextFn(prevFn(value));
		},
		value => value
	);
};

LuckyWinty avatar Feb 09 '20 14:02 LuckyWinty

compose也是正常顺序执行吧?只是变成洋葱模型了?你看一下@LuckyWinty:

const compose = (...fns) => {
	return fns.reduce(
		(prevFn, nextFn) => {
			return value => nextFn(prevFn(value));
		},
		value => value
	);
};

const arrFn = [
  () => {console.log(1)},
  () => {console.log(2)},
  () => {console.log(3)},
  () => {console.log(4)},
  () => {console.log(5)},
];

compose(...arrFn)();

/*
1
2
3
4
5
*/

shen-zhao avatar Feb 21 '20 06:02 shen-zhao

compose也是正常顺序执行吧?只是变成洋葱模型了?你看一下@LuckyWinty:

const compose = (...fns) => {
	return fns.reduce(
		(prevFn, nextFn) => {
			return value => nextFn(prevFn(value));
		},
		value => value
	);
};

const arrFn = [
  () => {console.log(1)},
  () => {console.log(2)},
  () => {console.log(3)},
  () => {console.log(4)},
  () => {console.log(5)},
];

compose(...arrFn)();

/*
1
2
3
4
5
*/

嗯,也可以正向的函数式编程,webpack里面是反向的。改为reduceRight吧

LuckyWinty avatar Feb 25 '20 03:02 LuckyWinty