如何调试运行时 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',.....
  .....
}