Typescript 运行时错误:无法读取未定义的属性“length”。

6

我有一个使用Typescript (版本为3.6.3)的React项目,

当我运行npm run build时出现了Typescript运行时错误:

ERROR in [internal] INTERNAL ERROR: Cannot read property 'length' of undefined stack trace: TypeError: Cannot read property 'length' of undefined at unescapeLeadingUnderscores

我发现导致这个问题的原因是LogRocket报告器中的某些内容,这是通过对typescrit.js进行console.log触发错误的Typescript对象:

{
  identifier: NodeObject {
    pos: -1,
    end: -1,
    flags: 8,
    modifierFlagsCache: 0,
    transformFlags: 0,
    parent: undefined,
    kind: 149,
    left: IdentifierObject {
      pos: -1,
      end: -1,
      flags: 8,
      modifierFlagsCache: 0,
      transformFlags: 0,
      parent: undefined,
      escapedText: 'LR',
      originalKeywordKind: undefined,
      autoGenerateFlags: 0,
      autoGenerateId: 0,
      emitNode: [Object],
      symbol: [SymbolObject]
    },
    right: IdentifierObject {
      pos: -1,
      end: -1,
      flags: 8,
      modifierFlagsCache: 0,
      transformFlags: 0,
      parent: undefined,
      escapedText: 'LogRocket',
      originalKeywordKind: undefined,
      autoGenerateFlags: 0,
      autoGenerateId: 0,
      emitNode: [Object],
      symbol: [SymbolObject]
    }
  }
}

非常感谢您的帮助。

tsconfig

{
  "compilerOptions": {
    // Allow importing like `import React from 'react'`
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "module": "esNext",

    // Resolve modules using Node-resolution algorithm
    "moduleResolution": "node",

    // Set React as the JSX factory
    "jsx": "react",

    // Include typings from built-in lib declarations
    "lib": ["es2019", "dom", "dom.iterable", "webworker"],

    // Include module source maps for debugging
    "sourceMap": true,
    "baseUrl": ".",
    "skipLibCheck": true,
    "target": "ES2020"
  },
  "exclude": ["node_modules"]
}

堆栈跟踪:

类型错误:无法读取未定义的属性“length” 在 unescapeLeadingUnderscores (C:\Users\user1\Development\Proj\node_modules\typescript\lib\typescript.js:13569:19) 在 Object.idText (C:\Users\user1\Development\Proj\node_modules\typescript\lib\typescript.js:13573:16) 在 typeToTypeNodeHelper (C:\Users\user1\Development\Proj\node_modules\typescript\lib\typescript.js:35286:57) 在 addPropertyToElementList (C:\Users\user1\Development\Proj\node_modules\typescript\lib\typescript.js:35680:59) 在 createTypeNodesFromResolvedType (C:\Users\user1\Development\Proj\node_modules\typescript\lib\typescript.js:35630:25) 在 createTypeNodeFromObjectType (C:\Users\user1\Development\Proj\node_modules\typescript\lib\typescript.js:35460:35) 在 createAnonymousTypeNode (C:\Users\user1\Development\Proj\node_modules\typescript\lib\typescript.js:35412:42) 在 typeToTypeNodeHelper (C:\Users\user1\Development\Proj\node_modules\typescript\lib\typescript.js:35320:28) 在 C:\Users\user1\Development\Proj\node_modules\typescript\lib\typescript.js:35114:106 在 withContext (C:\Users\user1\Development\Proj\node_modules\typescript\lib\typescript.js:35155:37)

webpack.config.js

const path = require('path')
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const webpack = require('webpack')
const cmd = require('commander')
const outputdir = path.resolve(__dirname, 'dist')
const flat = require('flat')
const {BundleAnalyzerPlugin} = require('webpack-bundle-analyzer')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ssr = require('./websrc/ssrRegistered.js')
const CopyPlugin = require('copy-webpack-plugin')
const WorkerPlugin = require('worker-plugin')
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin')
var HardSourceWebpackPlugin = require('hard-source-webpack-plugin')

const getEnvVars = () => {
  const vars = flat({process: {env: process.env}})
  Object.keys(vars).forEach(key => (vars[key] = JSON.stringify(vars[key])))

  return vars
}

const htmlMinifyOpts = {
  collapseWhitespace: true,
  collapseBooleanAttributes: true,
  minifyCSS: true,
  removeComments: true,
  removeRedundantAttributes: true,
  removeScriptTypeAttributes: true,
  removeStyleLinkTypeAttributes: true,
  useShortDoctype: true
}
cmd
  .option('--mode [mode]', '', process.env.NODE_ENV || 'development')
  .option('--report')
  .option('--debug')
  .option('--page [page]', '', '') // page for dev server to open
  .parse(process.argv)
const mode = cmd.mode

const opts = {
  entry: {app: './websrc/app.tsx'},
  output: {
    filename: '[name]-[chunkhash].js',
    path: outputdir,
    publicPath: '/',
    // show relative paths in sourcemaps
    devtoolModuleFilenameTemplate: '[resource-path]',
    devtoolFallbackModuleFilenameTemplate: '[resource-path]',
    pathinfo: false
  },
  mode,
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          cacheDirectory: true,
          cacheCompression: false
        }
      },
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        loader: 'ts-loader',
        options: {
          transpileOnly: true,
          experimentalWatchApi: true
        }
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: {
          loader: 'file-loader'
        }
      }
    ]
  },
  devServer: {
    contentBase: outputdir,
    open: true,
    openPage: path.normalize(cmd.page),
    overlay: {
      errors: true
    },
    historyApiFallback: true
    // host: '0.0.0.0'
  },
  devtool: mode === 'production' ? 'source-map' : 'source-map',
  optimization: {
    runtimeChunk: 'single'
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: 'proj1',
      filename: 'index.html',
      template: 'websrc/index.tsx',
      inject: false,
      ssr: ssr({outputdir})(),
      mode,
      minify: mode === 'production' ? htmlMinifyOpts : {}
    }),
    new webpack.DefinePlugin(getEnvVars()),
    new CopyPlugin(['websrc/static']),
    new WorkerPlugin({globalObject: 'self'}),
    new ForkTsCheckerWebpackPlugin(),
    new HardSourceWebpackPlugin()
  ],
  resolve: {
    modules: [__dirname, 'node_modules'],
    extensions: ['.ts', '.tsx', '.js']
  },
  resolveLoader: {
    modules: ['node_modules']
  }
}

if (cmd.report) {
  opts.plugins.push(new BundleAnalyzerPlugin({analyzerMode: 'static'}))
}

if (cmd.debug) console.log(opts) // eslint-disable-line no-console

module.exports = opts

1
请在您初始化 unescapeLeadingUnderscores 或使用 unescapeLeadingUnderscores.length 的代码处发布。 - zerocewl
@zerocewl 我试过了,还是一样的:( 我无法指出我最近做出的任何更改.. - user3378165
1
@AluanHaddad 请查看已编辑的问题。 - user3378165
1
@AluanHaddad 不,我没有使用 create-react-app,我在问题中添加了 package.json - user3378165
1
你能否创建一个最小的 Github/GitLab/Bitbucket 仓库,以便我们可以重现这个问题?只需要包含触发此错误的最小配置。仅凭文件几乎无法帮助您。谢谢 :) - a1300
显示剩余10条评论
1个回答

1
经过一些研究,看起来您可能遇到了Typescript GitHub上问题部分列出的错误。

https://github.com/microsoft/TypeScript/issues/21801

经过审查,我的建议是在整个应用程序中进行一些空值检查。我猜测您可能遇到了应用程序或组件初始化时的某些竞争条件。希望这可以帮助您,祝好运!


@user3378165,你的应用程序中可能有一些动态函数名称吗?这可能会导致此类错误。请参见:https://github.com/microsoft/TypeScript/issues/33604 和 https://github.com/microsoft/vscode/issues/78658 - a1300

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接