写一个处理js的错误的loader

本文介绍如何创建一个webpack loader,用于自动在异步JS函数中添加try-catch,避免手动添加带来的错误风险,提升项目维护效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写一个处理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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值