webpack tabable 为什么选择实时 generateCode?

2021-12-10 11:51:52 +08:00
 Alander

tabable 中的各种 hook 最终被 call 的时候,会通过 new Function(args, codeContent) 的形式生成一个函数

我好奇的是为什么它一定要用这种方式?例如:

case "sync":
				if (!rethrowIfPossible) {
					code += `var _hasError${tapIndex} = false;\n`;
					code += "try {\n";
				}
				if (onResult) {
					code += `var _result${tapIndex} = _fn${tapIndex}(${this.args({
						before: tap.context ? "_context" : undefined
					})});\n`;
				} else {
					code += `_fn${tapIndex}(${this.args({
						before: tap.context ? "_context" : undefined
					})});\n`;
				}
				if (!rethrowIfPossible) {
					code += "} catch(_err) {\n";
					code += `_hasError${tapIndex} = true;\n`;
					code += onError("_err");
					code += "}\n";
					code += `if(!_hasError${tapIndex}) {\n`;
				}
				if (onResult) {
					code += onResult(`_result${tapIndex}`);
				}
				if (onDone) {
					code += onDone();
				}
				if (!rethrowIfPossible) {
					code += "}\n";
				}
				break;

可以看见是通过字符串生成 code 内容。

那为什么不直接将 callTap 的方法写死呢?

function call(...args) {
  for (let tap of tapArr) {
    tap.fn.apply(null, args);
  }
}

这样不行吗?两者有什么区别? tabable 选择上面那种事为了解决什么问题呢?有大佬提个醒吗?

647 次点击
所在节点    程序员
1 条回复
Opportunity
2021-12-10 23:51:12 +08:00
Eval function ,经典性能榨汁机

比如这个也是
https://www.zhihu.com/question/276403215/answer/386917514

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/821298

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX