使用Ace.js打造自己的WebIDE

AdminPi, 前端, 2021-04-12 18:10:00

临时改下代码,这种需求对于程序员群体来说,再平常不过了!

手头刚好没有IDE怎么办?

用记事本吧,经常出现编码问题;下载一个吧,又太费事!

难道就没有更好的选择?

当然有,找一个WebIDE;但是注册账号又太麻烦!

作为程序员的我们,为什么不自己打造一款呢?

说干就干!

今天我们主要介绍一款基于浏览器的代码编辑器框架:

Ace (Ajax.org Cloud9 Editor)

她支持超过120种语言的语法高亮显示,并且主题个数超过20个,囊括了大部分IDE的配色方案;对于临时改改代码这种需求来说,已经完全足够。

把Ace嵌入到自己的网页,也非常的简单:

<div id="editor">
&lt;?php
	echo 'Hello World!';
?&gt;
</div>
<script src="src/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
    var editor = ace.edit("editor");
</script>

注意:必须设置div的宽和高,并且position需要设置成absolute或者relative,才能生效。

#editor {
    position: absolute;
    width: 500px;
    height: 500px;
}

配置编辑器的主题:

editor.setTheme("ace/theme/gruvbox");

配置编辑器以支持PHP语言:

editor.session.setMode("ace/mode/php");

各种配置参数请参考官方Wiki:

https://github.com/ajaxorg/ace/wiki/Configuring-Ace

下面贴一个完整的示例代码:

<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Ace-WebIDE</title>
  <style type="text/css" media="screen">
    body {
        overflow: hidden;
    }

    #editor {
        position: absolute;
        margin: 0;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
    }
  </style>
</head>
<body>

<pre id="editor">
&lt;?php
	echo 'Hello World!';
?&gt;
</pre>

<script src="https://cdn.staticfile.org/ace/1.4.9/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/gruvbox");
    editor.session.setMode("ace/mode/php");
  
  
  editor.setOptions({
    showPrintMargin  : false,
    fontSize : '1rem'
});

</script>

</body>
</html>

© 2024