如何调试运行时类型错误

How to debug runtime TypeError

我使用 webpack 构建了一个 React+Typescript 包。当我 运行 它并在浏览器中检查控制台时,我看到了这个神秘的堆栈跟踪。

错误发生在启动后的 1 秒内,并且是控制台中的第一条消息。

TypeError: n is not a function
    at bundle.js:2
    at Array.map (<anonymous>)
    at Gc.getBars (bundle.js:2)
    at Gc.drawOnCanvas (bundle.js:2)
    at X.drawOnCanvas (bundle.js:2)
    at X.componentDidUpdate (bundle.js:2)
    at X.componentDidMount (bundle.js:2)
    at hs (bundle.js:2)
    at Dl (bundle.js:2)
    at t.unstable_runWithPriority (bundle.js:2)

问题是,我不知道错误存在于代码的哪个位置,因为堆栈跟踪信息非常少。

如何找出问题出在哪一行代码?

这是我的 tsconfig.json

{
  "compilerOptions": {
    "target": "es5",                                /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
    "module": "commonjs",                           /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "strict" : true,
    "esModuleInterop": true,                        /* Enables emit 
    /* Advanced Options */
    "skipLibCheck": true,                           /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true,        /* Disallow inconsistently-cased references to the same file. */
    "jsx" : "react",
  }
}

这是我的 webpack.config.js


const path = require("path");
const HtmlWebPackPlugin = require("html-webpack-plugin");


const CopyPlugin = require("copy-webpack-plugin");


const htmlPlugin = new HtmlWebPackPlugin({
  template: "./src/index.html",
});

module.exports = {
  entry: "./src/index.tsx",
  

  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
      {
        test: /\.m?js/,
        resolve: {
          fullySpecified: false
        }
      }
    ],
  },


  resolve: {
    extensions: [".tsx", ".ts", ".js"],
    symlinks: true
  },

  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist")
  },

  plugins: [
    htmlPlugin,
    new CopyPlugin({
      patterns: [
        { from: "public" }
      ],
    }),
  ],


  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    compress: true,
    port: 9000 ,

    
  },

};

如果您提供 webpack.config.js 文件会很有帮助

一般来说,我会做

 node --inspect-brk=9229 ./node_modules/webpack/bin/webpack.js --config webpack.config.js --colors

调试 webpack 配置问题。

官方文档建议,node-nightly。我个人没用过。

只需将 this 添加到您的 webpack.config

module.exports = {
  entry: "./src/index.tsx",
  

  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
      {
        test: /\.m?js/,
        resolve: {
          fullySpecified: false
        }
      }
    ],
  },
  devtool: 'source-map',
  .....
  .....
}