首页 > 建站教程 > 编辑器、IDE >  script引入monaco editor编辑器时报错Can only have one anonymous define call per script file正文

script引入monaco editor编辑器时报错Can only have one anonymous define call per script file

在使用script引入方式调用monac editor编辑器时,代码如下,编辑器可以顺利显示,并无报错:

<script>
  var require = {
    paths: { vs: "./libs/monaco-editor/min/vs" },
    "vs/nls": { availableLanguages: { "*": "zh-cn" } },
  };
</script>
<script src="./libs/monaco-editor/min/vs/loader.js"></script>
<script src="./libs/monaco-editor/min/vs/editor/editor.main.nls.js"></script>
<script src="./libs/monaco-editor/min/vs/editor/editor.main.nls.zh-cn.js"></script>
<script src="./libs/monaco-editor/min/vs/editor/editor.main.js"></script>
<script>
  var editor = monaco.editor.create(document.body, {
    value: "// monaco editor example",
    language: "javascript",
    theme: "vs-dark",
  });
  
  let codeStr = `
import monaco from "monaco-editor";
var editor = monaco.editor.create(document.body, {
value: ["function x() {", '\tconsole.log("Hello world!");', "}"].join(
"\\n"
),
language: "javascript",
});
`;
editor.setValue(codeStr);
</script>


注:Monaco editor代码是npm install得到,然后拷贝到libs下的。


但是实际上在项目中按照这个方法引入后,却报错了:

Can only have one anonymous define call per script file


这是因为monaco的资源文件中有个判断,不能一个项目中有两个define的定义函数,因为monaco需要自己的定义。所以避免define方法互相污染而报错,或者资源文件没加载。这可能是项目中其他js也定义了define。解决方法如下:

<link rel="stylesheet" href="./libs/monaco-editor/min/vs/editor/editor.main.css" />
<script>
var require = {
paths: { vs: "./libs/monaco-editor/min/vs" },
"vs/nls": { availableLanguages: { "*": "zh-cn" } },
};
</script>
<script src="./libs/monaco-editor/min/vs/loader.js"></script>
<script src="./libs/monaco-editor/min/vs/editor/editor.main.nls.js"></script>
<script src="./libs/monaco-editor/min/vs/editor/editor.main.nls.zh-cn.js"></script>
<script src="./libs/monaco-editor/min/vs/editor/editor.main.js"></script>
<script>
// 在这里删除 define的amd属性
if('function' === typeof define && define.amd) {
delete define.amd;
}
</script>
// 此为monaco初始化代码
<script src="./libs/builder/monaco-editor.js"></script>