0

我想为我的代码添加async-catch-loader自动注入try catch。我的项目基于 Vue CLI 和 TypeScript。所以我需要使用 webpack-chain 来改变tswebpack 的规则,如下图所示:

{
  test: /\.m?jsx?$/,
  enforce: 'pre',
  use: [
    {
      loader: '/Users/wjc/Documents/company/project/demos/async-test/node_modules/cache-loader/dist/cjs.js',
      options: {
        cacheDirectory: '/Users/wjc/Documents/company/project/demos/async-test/node_modules/.cache/ts-loader',
        cacheIdentifier: '41bf2514'
      }
    },
    {
      loader: '/Users/wjc/Documents/company/project/demos/async-test/node_modules/babel-loader/lib/index.js'
    },
    {
      loader: 'async-catch-loader',
      options: {
        catchCode: 'console.error(\'wujingchang\')'
      }
    }
    {
      loader: '/Users/wjc/Documents/company/project/demos/async-test/node_modules/ts-loader/index.js',
      options: {
        transpileOnly: true,
        appendTsSuffixTo: [
          '\\.vue$'
        ],
        happyPackMode: false
      }
    },
  ]
},

但是,我不知道如何添加async-catch-loader之前和之后的ts规则。webpack-chain 有功能可以做到吗?babel-loaderts-loader

4

1 回答 1

0

我已经有了答案。webpack-chain没有提供实现它的方法。因此,我重写了ts规则,如下所示:

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()
}
于 2020-11-25T01:46:54.990 回答