auto-inject-async-catch-loader

1.1.2 • Public • Published

auto-inject-async-catch-loader

English | 中文

A webpack loader that can auto inject try catch code for async function. You can view the async-catch for basic config.

Based on it, I made two optimizations:

  1. Optimize the way for find parent
traverse(ast, {
  AwaitExpression(path) {
    if (path.findParent((path) => t.isTryStatement(path.node))) {
      return;
    }
    const blockParent = path.findParent((path) =>
      t.isBlockStatement(path.node)
    );
    const tryCatchAst = t.tryStatement(
      blockParent.node,
      t.catchClause(
        t.identifier(options.identifier),
        t.blockStatement(catchNode)
      ),
      finallyNode && t.blockStatement(finallyNode)
    );
    blockParent.replaceWithMultiple([tryCatchAst]);
  },
});
  1. Support use TypeScript + Vue. At this time, the async function ast's type is ClassMethod, so i add the judge for ClassMethod to isAsyncFunction function:
const isAsyncFuncNode = (node) =>
  t.isFunctionDeclaration(node, {
    async: true,
  }) ||
  t.isArrowFunctionExpression(node, {
    async: true,
  }) ||
  t.isFunctionExpression(node, {
    async: true,
  }) ||
  t.isObjectMethod(node, {
    async: true,
  }) ||
  t.isClassMethod(node, {
    async: true,
  });

Usage(Vue CLI)

Develop in JavaScript:

chainWepack: (config) => {
  const jsRule = config.module.rule("js");
  jsRule
    .use("auto-inject-async-catch-loader")
    .loader("auto-inject-async-catch-loader")
    .end();
};

Develop in TypeScript:

chainWebpack: (config) => {
  const tsRule = config.module.rule("ts");
  tsRule.uses.clear();
  tsRule
    .use("cache-loader")
    .loader("cache-loader")
    .end()
    .use("babel-loader")
    .loader("babel-loader")
    .end()
    .use("auto-inject-async-catch-loader")
    .loader("auto-inject-async-catch-loader")
    .tap(() => {
      return {
        catchCode: "console.error(e)",
      };
    })
    .end()
    .use("ts-loader")
    .loader("ts-loader")
    .tap(() => {
      return {
        transpileOnly: true,
        appendTsSuffixTo: ["\\.vue$"],
        happyPackMode: false,
      };
    })
    .end();
};

Package Sidebar

Install

npm i auto-inject-async-catch-loader

Weekly Downloads

3

Version

1.1.2

License

MIT

Unpacked Size

14.7 kB

Total Files

18

Last publish

Collaborators

  • wjchumble