写一个处理js的错误的loader
js异步处理方案中,async和await在js使用中,很多人没有写try catch,在项目庞大的情况写,手动添加容易出错,所以想写一个loader,来统一处理。
1.搭建一个项目
- npm init -y
- 安装依赖 npm i
"@babel/generator": "^7.18.2",
"@babel/parser": "^7.18.5",
"@babel/traverse": "^7.18.5",
"@babel/types": "^7.18.4",
"html-webpack-plugin": "^5.5.0",
"webpack": "^5.73.0",
"webpack-cli": "^4.10.0"
2.配置webpack.cofnig.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
module.exports = {
mode:"development",
entry:'./src/app.js',
output:{
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
resolveLoader:{modules:[path.resolve(__dirname,'loaders'),'node_modules']},
module:{
rules:[
{
test:/\.js$/,
use:[
{
loader:'err-loader'
}
]
},
]
},
plugins: [
new HtmlWebpackPlugin({})
]
}
3.app.js
function cc (){
}
// 正常的函数
const ceshi = async (data) => {
if (data) {
return true
} else {
throw Error('这是个错误函数')
}
}
// 异步的es6函数
const user = async () => {
await ceshi(false)
}
user()
4.在loaders文件夹下添加err-loader
const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const generate = require('@babel/generator').default;
const t = require("@babel/types");
function loader(content, sourceMap, meta) {
const ast = parser.parse(content);
traverse(ast, {
'ArrowFunctionExpression|FunctionExpression|FunctionDeclaration': function (path) {
// 处理方法
const isAsyncFun = t.isFunctionDeclaration(path.node, {
async: true
}) || t.isArrowFunctionExpression(path.node, {
async: true
}) || t.isFunctionExpression(path.node, {
async: true
});
// 判断是否是异步函数
if (!isAsyncFun) { // 不是async函数就停止操作
return;
}
const bodyNode = path.get("body");
const FunNode = bodyNode.node.body;
if (!t.isTryStatement(FunNode[0])) {
// 说明没有try
const code = `
console.log(error);
`;
// 添加try的节点
const resultAst = t.tryStatement(
bodyNode.node,
// catch的节点
t.catchClause(t.identifier("error"),
t.blockStatement(parser.parse(code).program.body)
)
)
// 替换方法里面的内容
bodyNode.replaceWithMultiple([resultAst]);
}
}
})
// 通过load的callback方法 返回处理过的code
this.callback(null,generate(ast).code,sourceMap,meta);
}
module.exports = loader
https://juejin.cn/post/7155434131831128094