TypeScript + webpack构建报错与解决方案集合

1,730 阅读1分钟
  • TypeScript报错:Child process failed to process the request: Error: Debug Failure. False expression.

图片.png 在这里我使用了TypeScript v4.7.4的版本,导致报错。

解决方法:将typescript@4 的版本换成 typescript@3 的版本即可解决,npm i typescript@3 -D。现在使用的版本是v3.9.10。


  • 错误 TS2717: Subsequent property declarations must have the same type.

图片.png 解决方法:在tsconfig.json配置 compilerOptions 中添加配置项 "skipLibCheck": true。跳过声明文件d.ts的类型检查。

此配置有副作用,慎用!官方描述如下:

图片.png 这可以节省编译期间的时间,但代价是类型系统的准确性。 例如,两个库可以以不一致的方式定义同一类型的两个副本。 TypeScript不会对所有的d.ts文件进行全面检查,而是会对你的应用在源代码中特别引用的代码进行输入检查。


  • 错误 TS2613: Module '"/node_modules/@types/"' has no default export. | TS1259: Module '"/node_modules/@types/"' can only be default-imported using the 'esModuleInterop' flag

图片.png 图片.png 解决方法:在tsconfig.json配置 compilerOptions 中添加配置项 "allowSyntheticDefaultImports": true

官方描述如下: 图片.png


  • 错误 TS17004: Cannot use JSX unless the '--jsx' flag is provided.

React写Jsx时报错:无法使用 JSX,除非提供了 "--jsx" 标志。 图片.png 图片.png

解决方法:在tsconfig.json配置 compilerOptions 中添加配置项 "jsx": "react"


  • TypeError: Cannot read property 'render' of undefined | Cannot read property 'createElement' of undefined

在使用ts之后,会遇到这种问题,使用

import React from 'react'
import ReactDOM from 'react-dom'

默认导入时,系统识别不了,报上面的错误。而必须改成 import * as才不会报错。

import * as React from 'react'
import * as ReactDOM from 'react-dom'

解决方法:这是ts机制导致,可以通过在tsconfig.json配置 compilerOptions 中添加配置项 "esModuleInterop": true,就可以直接使用default import了,如import React from 'react',官方描述: 图片.png