谈谈 react-ace 一个用JavaScript系的可嵌入代码编辑器是如何使用的。
安装
yarn add reace-ace ace-builds
首先,react-ace 不用多说,主体包。虽然安装了 react-ace 后,node_modules 中会找到 ace-builds 但,这个并不足够让我们正常使用,需要手动再安装一下。如果启动的时候报 file-loader 错误,请按照提示安装 file-loader。
使用
首先,我们看看 ace-builds ,它提供了 如theme、mode等预建文件,可直接 import 使用。
// 引入对应的语言模式
import 'ace-builds/src-noconflict/mode-javascript';
// 引入对应的主题
import 'ace-builds/src-noconflict/theme-github';
// 下面两个是使用代码提示的时候需要引入的内容
import 'ace-builds/src-noconflict/ext-language_tools';
import 'ace-builds/webpack-resolver';
react-ace 使用
....
// 代码提示
const completers = [
{
name: 'name',
value: `"inputDemo1": {
"type": "string",
"maxLength": 12,
"minLength": 6,
"title": "普通 Input",
"x-component": "input",
"x-component-props": {
"placeholder": "如:请输入"
},
"description": "这是描述文字",
"x-rules": [{ "required": true, "message": "请输入" }]
},`,
score: 100,
meta: '输入框模板',
},
];
// 在onload方法中可以做代码提示
const complete = (editor: any) => {
editor.completers = [
// 自己的代码提示
{
getCompletions(
editor: any,
session: any,
pos: any,
prefix: any,
callback: any,
) {
callback(null, completers);
},
},
// 编辑器的代码提示
// ...editor.completers,
];
};
const handleBlur = () => {
// 做格式化代码
setEditorValue(jsonStringify(jsonParse(editorValue)));
}
...
<AceEditor
className={styles.editor}
value={editorValue}
mode="javascript"
theme="github"
onChange={onChange}
name="UNIQUE_ID_OF_DIV"
editorProps={{
$blockScrolling: true,
}}
setOptions={{
useWorker: false,
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
enableSnippets: true,
showLineNumbers: false,
tabSize: 2,
}}
onLoad={complete}
onBlur={handleBlur}
/>
...
这里失焦事件做格式化代码处理,为什么没有直接用,因为输入的内容中可能会用到正则,所以在 JSON.stringify 和 JSON.parse 中添加了处理。
const jsonParse = (value: string): any => {
return JSON.parse(value, (k: any, v: any) => {
try {
// 将正则字符串转成正则对象
if (eval(decodeURIComponent(v)) instanceof RegExp) {
return eval(decodeURIComponent(v));
}
return v;
} catch (e) {
return v;
// nothing
}
});
};
const jsonStringify = (value: object, type = 2): any => {
return JSON.stringify(
value,
(k: any, v: any) => {
if (v instanceof RegExp) {
return encodeURIComponent(v.toString());
}
return v;
},
type,
);
};
遇到的问题
1. 使用 代码提示 功能报错
'ace-builds/webpack-resolver',在 webpack 环境中使用必须要导入,但引入ace-builds/webpack-resolver 会构建很多无用的js文件(解决方案持续寻找中...)
这就是我 react-ace 探索之旅,内容不多,简单记录一下。
github仓库:demo