開發環境說明
當前的前端項目是基於Ionic4進行開發的,底層基於Angular8框架. 項目中使用到了threejs庫,之前版本用的是r0.108.0, 最近做了個版本升級,升級到了r0.111.0, 結果在編譯的時候報瞭如下幾種錯誤.
ERROR in ../node_modules/three/src/core/BufferAttribute.d.ts:21:6 - error TS1086: An accessor cannot be declared in an ambient context.
21 set needsUpdate( value: boolean );
// ...
ERROR in node_modules/three/src/renderers/WebGLRenderer.d.ts(35,31): error TS2304: Cannot find name 'OffscreenCanvas'.
node_modules/three/src/renderers/webgl/WebGLUtils.d.ts(3,43): error TS2304: Cannot find name 'WebGL2RenderingContext'.
可以見到主要出現了三種錯誤:
- An accessor cannot be declared in an ambient context
- Cannot find name 'OffscreenCanvas’
- Cannot find name 'WebGL2RenderingContext’
解決WebGL2RenderingContext
及OffscreenCanvas
問題
- 需要在tsconfig.app.ts的
types
字段增加如下聲明:
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": ["webgl2", "offscreencanvas"] // 這裏加
},
// ...
"exclude": ["test.ts", "**/*.spec.ts"]
}
- 手動安裝對應的包
npm i @types/offscreencanvas --save
npm i @types/webgl2 --save
# 當前默認下會安裝如下版本
# "@types/offscreencanvas": "^2019.6.0",
# "@types/webgl2": "0.0.5",
解決An accessor cannot be declared in an ambient context
問題
- 原因分析
這是由於已安裝的typescript
版本和three
庫所需的typescript版本不一致導致的,已安裝的typescript比較舊, 當前爲3.5.3
.
- 嘗試升級typescript
npm uninstall typescript
npm i typescript
# 默認重新安裝了3.7.3版本
重新構建的時候發現原有問題不報錯了, 但是出現了新的問題:
ionic build --prod --release
// ...
Angular Compiler requires TypeScript >=3.4.0 and <3.6.0 but 3.7.3 was found instead
說明目前Angular8最新支持的typescript版本要低於3.6? 一開始我就嘗試把Angular8升級到剛發佈不久的Angular9, 後來發現Ionic4還不支持Angular9, 這就有點尷尬了. IonicFramework 5正式版估計很快就發佈了,但是也沒看到對於這方面有什麼具體說法.
所以暫時用了個臨時的方法先解決這個問題, 就是粗暴的先禁用項目對typescript版本的檢查,在tsconfig.app.ts中新增的具體配置如下:
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": ["webgl2", "offscreencanvas"]
},
"angularCompilerOptions": {
// ...
"disableTypeScriptVersionCheck": true // 在這裏新加了一個配置選項
},
"exclude": ["test.ts", "**/*.spec.ts"]
}
到這裏,項目終於可以編譯通過了,暫時還沒發現其他的問題. 不過這個算是臨時解決吧,這叫掩耳盜鈴?始終要通過將各個庫升級到對應的版本纔行.