Ron*_*ton 5 javascript parsing webpack webpack-plugin
我正在编写一个代码分析 webpack 插件,它想在 webpack 包中查找函数名称的所有实例。
我为这个问题做了一个 repo:https : //github.com/RonPenton/webpack-parser-fail-demo
所以解析器真的很简单,就像这样:
class ParsePlugin {
apply(compiler) {
compiler.plugin('compilation', function (compilation, data) {
data.normalModuleFactory.plugin('parser', function (parser, options) {
parser.plugin(`call $findme`, function (expr) {
console.log("found $findme!");
});
});
});
}
Run Code Online (Sandbox Code Playgroud)
https://github.com/RonPenton/webpack-parser-fail-demo/blob/master/parse.js
我想要做的就是在代码中找到 $findme() 的所有实例并记录有关它们的信息。稍后,我什至可能最终更改电话,但那是另一天。
当我提供这个源文件时,一切都很好:https : //github.com/RonPenton/webpack-parser-fail-demo/blob/master/good.js
$findme("Testing");
$findme("Testing too...");
Run Code Online (Sandbox Code Playgroud)
当我运行 webpack 时,输出显示找到了两个实例:
found $findme!
found $findme!
Hash: a6555af5036af17d9320
Version: webpack 3.6.0
Time: 69ms
Asset Size Chunks Chunk Names
good.js 2.52 kB 0 [emitted] main
[0] ./good.js 47 bytes {0} [built]
Run Code Online (Sandbox Code Playgroud)
但是当我使用不同的入口点时,函数是在本地(https://github.com/RonPenton/webpack-parser-fail-demo/blob/master/bad.js)或外部模块(https ://github.com/RonPenton/webpack-parser-fail-demo/blob/master/bad2.js),解析器突然停止查找这些方法。
function $findme(input) {
console.log(input);
}
$findme("Testing");
$findme("Testing too...");
Run Code Online (Sandbox Code Playgroud)
====
import { $findme } from './findme';
$findme("Testing");
$findme("Testing too...");
Run Code Online (Sandbox Code Playgroud)
那么有什么关系呢?我尝试深入研究 webpack 源代码,据我所知,这似乎是故意的。但是实际上没有关于为什么这样做的文件,也没有评论。
这不是插件可以做到的吗?
我在这里先向您的帮助表示感谢。
奇怪的是,webpack 解析器仅在以某种方式调用或检索函数时才调用这些钩子。这就是为什么当以一种方式调用函数时你的钩子可以工作,但当它从某个地方导入时却不起作用。
我试图找到对对象方法的所有调用,但遇到了同样的问题。
另一个人提出的这个github问题有更多细节:https ://github.com/webpack/webpack/issues/9480
要解决这个问题,您需要欺骗 webpack 解析器,使其认为由于某种原因它不想调用挂钩的函数/方法调用是标识符,就像这里所做的那样: https: //github.com/aurelia/webpack -plugin/blob/9f6f7983312c66f857e79b744e4ec257cc287b8b/dist/InlineViewDependencyPlugin.js
您需要使用解析器“evaluate”挂钩返回一个自定义BasicEvaluatedExpression实例,该实例isIdentifier对于您想要查找的所有函数调用都设置为 true。然后call钩子将被完整表达式调用。就我而言,我需要包含函数及其参数的完整 CallExpression。
| 归档时间: |
|
| 查看次数: |
239 次 |
| 最近记录: |