Ace 编辑器模式不起作用

Ace editor mode not working

我正在尝试让语法高亮显示正常工作,但在更改模式时它不起作用

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.9/monokai.js"></script>
    <script="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.9/mode-javascript.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.9/ace.js"></script>
    <script src="scripts.js"></script>

scripts.js

var html = ace.edit("htmlEditor");
var css = ace.edit("cssEditor");
var js = ace.edit("jsEditor");

html.setTheme("ace/theme/monokai");
css.setTheme("ace/theme/monokai");
js.setTheme("ace/theme/monokai");

var JavaScriptMode = ace.require("ace/mode/javascript").Mode;
js.session.setMode(new JavaScriptMode());

您的 html 有错别字 <script=" 此外,主题和模式的脚本必须插入 ace.js

之后

最好将名称传递给ace,让它自己加载模式和主题

<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.9/ace.js"></script>
<div id="htmlEditor">&lt;html&gt;</div>
<div id="cssEditor">.css { color: red }</div>
<div id="jsEditor">var js</div>
<style>
html, body {
    height: 100%;
}
#htmlEditor, #cssEditor, #jsEditor  {
height:30%
}
</style>
<script>

var html = ace.edit("htmlEditor");
var css = ace.edit("cssEditor");
var js = ace.edit("jsEditor");

html.setTheme("ace/theme/monokai");
css.setTheme("ace/theme/monokai");
js.setTheme("ace/theme/monokai");

html.session.setMode("ace/mode/html");
css.session.setMode("ace/mode/css");
js.session.setMode("ace/mode/javascript");

</script>

让我回答这个问题的是我在调用 setMode

时遇到 404 错误

我遍历了代码以查看发生了什么,Ace 尝试 identify where Ace library 并且它的文件是 located,它在 script tags 中执行 by looking页面,所以 if 它有一个 lock finding the lib location,它把它设置为 basePath

但是如果 Ace 是 bundled 在一个缩小的主 js 文件 main.js 中,它将失败并且 return 404

解决这个问题

if (window.ace) {
    configureAce();
    //....
}

function configureAce() {
    // this is important in case of bundling , to have Ace knows where
    // its files are located (like themes, workers and modes)
    // and get them from that path
    window.ace.config.set("basePath", "/resources/js/lib/ace");
}