如何使用简单的 JavaScript 或 jQuery 在浏览器中初始化 Microsoft Monaco 编辑器

Sta*_* UI 10 javascript jquery monaco-editor

我正在尝试使用Microsoft Monaco初始化文本/代码编辑器。我想使用核心 JavaScript甚至 jQuery 但没有 NodeJS 依赖。那可能吗?

一些相关的例子:

获取 Monaco Editor 的价值

jsFiddle 中的示例

我有以下代码,但它不起作用:

    <!DOCTYPE html>
<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
</head>
<body>

<div id="container" style="width:800px;height:600px;border:1px solid grey"></div>

<script type="text/javascript" src="https://microsoft.github.io/monaco-editor/node_modules/monaco-editor/min/vs/loader.js"></script>


<script>
require.config({ paths: { 'vs': 'monaco-editor/min/vs' }});
require(['vs/editor/editor.main'], function() {
    window.editor = monaco.editor.create(document.getElementById('container'),                 {
        value: [
            'function x() {',
            '\tconsole.log("Hello world!");',
            '}'
        ].join('\n'),
        language: 'javascript'
    });
});

function save() {
   // get the value of the data
   var value = window.editor.getValue()
   saveValueSomewhere(value);     
}


</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮忙吗?

Pet*_*ter 18

我在下面添加了一个工作示例。关于你的另一个问题:

我想使用核心 JavaScript 甚至 jQuery 但没有 NodeJS 依赖。那可能吗?

monaco-editor 用 JavaScript 编写的(TypeScript 编译为 JavaScript),不使用 jQuery。Node 在您描述的上下文中并不真正相关。

请让我知道这可不可以帮你。

require.config({ paths: { 'vs': 'https://unpkg.com/monaco-editor@latest/min/vs' }});
window.MonacoEnvironment = { getWorkerUrl: () => proxy };

let proxy = URL.createObjectURL(new Blob([`
	self.MonacoEnvironment = {
		baseUrl: 'https://unpkg.com/monaco-editor@latest/min/'
	};
	importScripts('https://unpkg.com/monaco-editor@latest/min/vs/base/worker/workerMain.js');
`], { type: 'text/javascript' }));

require(["vs/editor/editor.main"], function () {
	let editor = monaco.editor.create(document.getElementById('container'), {
		value: [
			'function x() {',
			'\tconsole.log("Hello world!");',
			'}'
		].join('\n'),
		language: 'javascript',
		theme: 'vs-dark'
	});
});
Run Code Online (Sandbox Code Playgroud)
html, body, #container {
	position: absolute;
	left: 0;
	top: 0;
	width: 100%;
	height: 100%;
	margin: 0;
	padding: 0;
	overflow: hidden;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/monaco-editor@latest/min/vs/loader.js"></script>
<div id="container"></div>
Run Code Online (Sandbox Code Playgroud)

  • @Alvaro 这没有使用 RequireJS。Microsoft 创建了自己的“require”对象,用于配置 Monaco,但它不是 RequireJS(尽管它共享相同的对象名称)。 (3认同)