怎么统计Webpack组件的使用次数?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
我们知道 loader 的 source是文件的静态字符串如下图
最快的方案通过字符串统计用正则的方式一把梭,但是这样会有问题就是如果注释部分有的话也会被统计进去就不准确,所以我们可以通过 AST 的方式来实现,关于 ast 的概念有很多大佬都讲过了我就不啰嗦了
我这边是通过 @babel/parser 来分析的,我们先看下面这段代码在网站上的构成
import { Box } from '@material-ui/core';
import Autocomplete from '@material-ui/lab/Autocomplete';
我们可以看出路径 program => body ,然后声明类型是 type: ImportDeclaration,继续看如下构成
"source": {
"type": "StringLiteral",
"value": "@material-ui/core"
},
// 第二段
"source": {
type": "StringLiteral",
"value": "@material-ui/lab/Autocomplete"
},
我们发下这个字段里面的 value 有我们想要的包名所以第一段代码就是
const ast = parser.parse(source, {
sourceType: 'module',
plugins: ['jsx'],
});
const getImport = 'ImportDeclaration';
const getMaterialImport = packageName || '@material-ui';
const importAst = ast.program.body.filter(
// type 节点类型,这里我们去过滤 import 声明类型 同时去过滤
(i) => i.type === getImport && i.source.value.includes(getMaterialImport),
);
拿到相关的 ast 数组下一步就要去拿到组件名字了, 通过观察我们发现 specifiers 标识符这个字段里面有两个字段包含组件名:imported、local
imported 表示从导出模块导出的变量
local 表示导入后当前模块的变量
这里我取的 local, 因为下面这种方式并不会出现 imported 这个字段
import Autocomplete from '@material-ui/lab/Autocomplete';
这个时候包的名字也拿到了后面就简单了直奔主题贴完整代码了
const parser = require('@babel/parser');
const loaderUtils = require('loader-utils');
const total = {
len: 0,
components: {},
};
// 对象排序
const sortable = (obj) => Object.fromEntries(Object.entries(obj).sort(([, a], [, b]) => b - a));
module.exports = function(source) {
console.log(source, '--');
const options = loaderUtils.getOptions(this);
const { packageName = '' } = options;
const callback = this.async();
if (!packageName) return callback(null, source);
try {
// 解析成 ast
const ast = parser.parse(source, {
sourceType: 'module',
plugins: ['jsx'],
});
if (ast) {
setTimeout(() => {
const getImport = 'ImportDeclaration';
const getMaterialImport = packageName;
const importAst = ast.program.body.filter(
// type 节点类型,这里我们去过滤 import 声明类型 同时去过滤
(i) => i.type === getImport && i.source.value.includes(getMaterialImport),
);
total.len = total.len + importAst.length;
for (let i of importAst) {
const { specifiers = [] } = i;
for (let s of specifiers) {
if (s.local) {
const { name } = s.local;
total.components[name] = total.components[name] ? total.components[name] + 1 : 1;
}
}
}
total.components = sortable(total.components);
console.log(total, 'total');
callback(null, source);
}, 0);
} else callback(null, source);
} catch (error) {
callback(null, source);
}
};
调用 loader
{
test: /\.(jsx|)$/,
exclude: /node_modules/,
include: [appConfig.eslintEntry],
use: [
{
loader: path.resolve(__dirname, './loader/total.js'),
options: {
packageName: '@material-ui',
},
},
],
},
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。