2

webpack tabable 为什么选择实时 generateCode?

 2 years ago
source link: https://www.v2ex.com/t/821298
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  程序员

webpack tabable 为什么选择实时 generateCode?

  Alander · 5 小时 3 分钟前 · 103 次点击

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 选择上面那种事为了解决什么问题呢?有大佬提个醒吗?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK