LuckyWinty / fe-weekly-questions

A pro to record some interview questions every week...
MIT License
341 stars 34 forks source link

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

Open LuckyWinty opened 4 years ago

LuckyWinty commented 4 years ago

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

webpack 里面的 compose 代码为:

const compose = (...fns) => {
    return fns.reduceRight(
        (prevFn, nextFn) => {
            return value => nextFn(prevFn(value));
        },
        value => value
    );
};
shen-zhao commented 4 years ago

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
*/
LuckyWinty commented 4 years ago

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吧