前言
由于 ace-editor 官網并沒有提供各個前端框架Vue,React,Angular的直接使用的適配版本, 所以本次使用的vue3-ace-editor 是個人開源者維護的版本,原生是支持 SFC 模版用的,由于我這里習慣使用 JSX 或 TSX的方式,所以遇到了兩個小問題,特此記錄
在 JSX / TSX 模式下,使用 v-model 綁定 value 編譯報錯
如下代碼:
<VAceEditor v-model:value={this.textContent}onInit={this.editorInit} lang="yaml" theme="chrome" minLines={this.editorMinLines} maxLines={this.editorMaxLines}/>
執行 npm run build 報錯:
v-model:value is not assignable to type 'IntrinsicAttributes & { [x: `on${Capitalize<string>}`]: (...args: any[]) => any; lang?: string; theme?: string; readonly?: boolean; wrap?: boolean; printMargin?: number | boolean; ... 10 more ...; readonly minLines?: number; }'.
大致意思就是 VAceEditor 的必選屬性 value 沒有傳,所以編譯失敗,看了一眼 VAceEditor 封裝的源碼,確實是要求有 value 屬性的:
猜測是這個 tsx 里面的 v-model:value 不會被 VAceEditor 這個 SFC 組件識別,因為 value 屬性是一個特殊的字段名,之前用過非 value 字段名的綁定都是正常的,這次 和 組件的 props 屬性名重復了就編譯失敗了,臨時用了hack的辦法,解決了這個問題,因為提示缺 value 屬性,那我就給你再傳一個唄,雖然看著有點奇怪,但確實能正常運行,且雙向數據綁定也是ok的:
<VAceEditor v-model:value={this.textContent}value={this.textContent}onInit={this.editorInit} lang="yaml" theme="chrome" minLines={this.editorMinLines} maxLines={this.editorMaxLines}/>
在 JSX / TSX 模式下,兩個TSX組件,同時注冊了 ace/mode/sh,會導致報 ace is not define 錯誤
import {VAceEditor} from 'vue3-ace-editor';
import ace, {config} from 'ace-builds';
import modeJson from 'ace-builds/src-noconflict/mode-json';
import modeYaml from 'ace-builds/src-noconflict/mode-yaml';
import modeGroovy from 'ace-builds/src-noconflict/mode-groovy';
import themeChrome from 'ace-builds/src-noconflict/theme-chrome';
import modeSh from "ace-builds/src-noconflict/mode-sh";
import 'ace-builds/src-noconflict/ext-language_tools';config.setModuleUrl("ace/mode/chrome", themeChrome);
config.setModuleUrl("ace/mode/yaml", modeYaml);
config.setModuleUrl("ace/mode/sh", modeSh);
config.setModuleUrl("ace/mode/json", modeJson);
config.setModuleUrl("ace/theme/github", modeGroovy);
ace.require("ace/ext/language_tools");
具體原因還不清楚,移除了一個 ace/mode/sh 就正常了
總結
在使用 Vue +TS + TSX + Vite 用法來開發業務的時候,在打包時候很容易出現問題,因為打包是強校驗,所以在執行 npm run dev 的時候并不一定會提示出來,所以在開發完一個組件或者一部分業務時候,可以提前 build 一次,將問題提前暴露出來,這樣排查定位起來會比較好定位