monaco-editor Documentation

A browser based code editor

46,873 stars JavaScript JavaScript 7 files ยท ~5,440 tokens #browser#editor#monaco-editor#typescript#vscode
RAW Doc

Docker & Self-Hosted Deployment Verified OCI

Deploy monaco-editor on any server, homelab, or cloud container platform.

1-Click Terminal Command
bash (docker run)
docker run -d --name monaco-editor --restart always microsoft/monaco-editor:latest

Technical Documentation: microsoft/monaco-editor

โ„น๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference

Overview (`README.md`)

Monaco Editor




The Monaco Editor is the fully featured code editor from VS Code. Check out the VS Code docs to see some of the supported features.

Try it out

Try out the editor and see various examples in our interactive playground.

The playground is the best way to learn about how to use the editor, which features is supports, to try out different versions and to create minimal reproducible examples for bug reports.

Installing

text
> npm install monaco-editor

You will get:

  • inside /esm: ESM version of the editor (compatible with e.g. webpack)
  • monaco.d.ts: this specifies the API of the editor (this is what is actually versioned, everything else is considered private and might break with any release).

:warning: The monaco editor also ships an AMD build for backwards-compatibility reasons, but the AMD support is deprecated and will be removed in future versions.

Localization

To load the editor in a specific language, make sure that the corresponding nls script file is loaded before the main monaco editor script. For example, to load the editor in German, include the following script tag:

html
<script src="path/to/monaco-editor/esm/nls.messages.de.js"></script>

Check the sources for available languages.

Concepts

Monaco editor is best known for being the text editor that powers VS Code. However, it's a bit more nuanced. Some basic understanding about the underlying concepts is needed to use Monaco editor effectively.

Models

Models are at the heart of Monaco editor. It's what you interact with when managing content. A model represents a file that has been opened. This could represent a file that exists on a file system, but it doesn't have to. For example, the model holds the text content, determines the language of the content, and tracks the edit history of the content.

URIs

Each model is identified by a URI. This is why it's not possible for two models to have the same URI. Ideally when you represent content in Monaco editor, you should think of a virtual file system that matches the files your users are editing. For example, you could use file:/// as a base path. If a model is created without a URI, its URI will be inmemory://model/1. The number increases as more models are created.

Editors

An editor is a user facing view of the model. This is what gets attached to the DOM and what your users see visually. Typical editor operations are displaying a model, managing the view state, or executing actions or commands.

Providers

Providers provide smart editor features. For example, this includes completion and hover information. It is not the same as, but often maps to language server protocol features.

Providers work on models. Some smart features depends on the file URI. For example, for TypeScript to resolve imports, or for JSON IntelliSense to determine which JSON schema to apply to which model. So it's important to choose proper model URIs.

Disposables

Many Monaco related objects often implement the .dispose() method. This method is intended to perform cleanups when a resource is no longer needed. For example, calling model.dispose() will unregister it, freeing up the URI for a new model. Editors should be disposed to free up resources and remove their model listeners.

Documentation

Issues

Create issues in this repository for anything related to the Monaco Editor. Please search for existing issues to avoid duplicates.

FAQ

โ“ What is the relationship between VS Code and the Monaco Editor?

The Monaco Editor is generated straight from VS Code's sources with some shims around services the code needs to make it run in a web browser outside of its home.

โ“ What is the relationship between VS Code's version and the Monaco Editor's version?

None. The Monaco Editor is a library and it reflects directly the source code.

โ“ I've written an extension for VS Code, will it work on the Monaco Editor in a browser?

No.

Note: If the extension is fully based on the LSP and if the language server is authored in JavaScript, then it would be possible.

โ“ Why all these web workers and why should I care?

Language services create web workers to compute heavy stuff outside of the UI thread. They cost hardly anything in terms of resource overhead and you shouldn't worry too much about them, as long as you get them to work (see above the cross-domain case).

โ“ I see the warning "Could not create web worker". What should I do?

HTML5 does not allow pages loaded on file:// to create web workers. Please load the editor with a web server on http:// or https:// schemes.

โ“ Is the editor supported in mobile browsers or mobile web app frameworks?

No.

โ“ Why doesn't the editor support TextMate grammars?

Contributing / Local Development

We are welcoming contributions from the community!
Please see CONTRIBUTING for details how you can contribute effectively, how you can run the editor from sources and how you can debug and fix issues.

Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

License

Licensed under the MIT License.


Overview (`monaco-lsp-client/README.md`)

Monaco LSP Client

Provides a Language Server Protocol (LSP) client for the Monaco Editor.

This package is in alpha stage and might contain many bugs.


Overview (`samples/README.md`)

Monaco Editor Samples

Standalone HTML samples showing how to integrate the Monaco Editor.

Running

bash
git clone https://github.com/microsoft/monaco-editor.git
cd monaco-editor
cd samples
npm install .
npm run simpleserver

Go to localhost:8888 and explore the samples!

Loading variations

  • browser-amd-editor: running in a browser using AMD lazy loading.
  • browser-script-editor: running in a browser using AMD synchronous loading via <script> tags.
  • browser-esm-webpack: running in a browser using webpack.
  • browser-esm-webpack-small: running in a browser using webpack (only a subset of the editor).
  • electron-amd: running in electron.
  • nwjs-amd and nwjs-amd-v2: running in nwjs. it is reported that v2 works and the initial version does not.

Other examples & techniques

  • browser-amd-diff-editor: running the diff editor in a browser.
  • browser-amd-iframe: running in an ``.
  • browser-amd-localized: running with the German locale.
  • browser-amd-monarch: running with a custom language grammar written with Monarch.
  • browser-amd-shared-model: using the same text model in two editors.

License

MIT


Overview (`webpack-plugin/README.md`)

Monaco Editor Webpack Loader Plugin

A plugin to simplify loading the Monaco Editor with webpack.

Installing

sh
npm install monaco-editor-webpack-plugin

Using

  • webpack.config.js:
js
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
const path = require('path');

module.exports = {
	entry: './index.js',
	output: {
		path: path.resolve(__dirname, 'dist'),
		filename: 'app.js'
	},
	module: {
		rules: [
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader']
			},
			{
				test: /\.ttf$/,
				type: 'asset/resource'
			}
		]
	},
	plugins: [new MonacoWebpackPlugin()]
};

If using Webpack 4 or lower, it is necessary to use the file-loader instead of Asset Modules like the code below:

js
{
	test: /\.ttf$/,
	use: ['file-loader']
}
  • index.js:
js
import * as monaco from 'monaco-editor';
// or import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
// if shipping only a subset of the features & languages is desired

monaco.editor.create(document.getElementById('container'), {
	value: 'console.log("Hello, world")',
	language: 'javascript'
});

Options

Options can be passed in to MonacoWebpackPlugin. They can be used to generate a smaller editor bundle by selecting only certain languages or only certain editor features:

  • filename (string) - custom filename template for worker scripts, respects the same options as loader-utils' interpolateName. Useful for adding content-based hashes so that files can be served with long-lived caching headers.

    • default value: '[name].worker.js'.
  • publicPath (string) - custom public path for worker scripts, overrides the public path from which files generated by this plugin will be served. This wins out over Webpack's dynamic runtime path and can be useful to avoid attempting to load workers cross-origin when using a CDN for other static resources. Use e.g. '/' if you want to load your resources from the current origin..

    • default value: ''.
  • languages (string[]) - include only a subset of the languages supported. By default, all languages shipped with the monaco-editor will be included.

    Some languages share the same web worker. If one of the following languages is included, you must also include the language responsible for instantiating their shared worker:

    Language Instantiator
    javascript typescript
    handlebars html
    scss, less css

    To view a list of all available languages, you can run import metadata from 'monaco-editor/esm/metadata'; console.log(metadata.languages);.

  • features (string[]) - include only a subset of the editor features. By default, all features shipped with the monaco-editor will be included. Instead of enumerating included features, it is also possible to exclude certain default features prefixing them with an exclamation mark '!'.

    To view a list of all available features, you can run import metadata from 'monaco-editor/esm/metadata'; console.log(metadata.features);.

  • globalAPI (boolean) - specify whether the editor API should be exposed through a global monaco object or not. This option is applicable to 0.22.0 and newer version of monaco-editor. Since 0.22.0, the ESM version of the monaco editor does no longer define a global monaco object unless global.MonacoEnvironment = { globalAPI: true } is set (change log).

    • default value: false.

Version Matrix

monaco-editor-webpack-plugin monaco-editor
7.*.* >= 0.31.0
6.*.* 0.30.*
5.*.* 0.29.*
4.*.* 0.25.*, 0.26.*, 0.27.*, 0.28.*
3.*.* 0.22.*, 0.23.*, 0.24.*
2.*.* 0.21.*
1.9.* 0.20.*
1.8.* 0.19.*
1.7.* 0.18.*

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct.
For more information see the Code of Conduct FAQ or
contact [email protected] with any additional questions or comments.


Overview (`samples/legacy/README.md`)

These AMD samples are not supported anymore and will be removed in future releases.
Please use the ESM version of the editor!


Overview (`build/esm/rollup-plugin-keep-css-imports/README.md`)

See https://www.npmjs.com/package/rollup-plugin-keep-css-imports.
Compare index.mjs with index.original.mjs to see the patch.


Integrate Esm (`docs/integrate-esm.md`)

Integrating the ESM version of the Monaco Editor

Using webpack

Here is the most basic script that imports the editor using ESM with webpack.

More self-contained samples are available in the samples folder.


Option 1: Using the Monaco Editor WebPack Plugin

This is the easiest method, and it allows for options to be passed into the plugin in order to select only a subset of editor features or editor languages. Read more about the Monaco Editor WebPack Plugin, which is a community authored plugin.

  • index.js
js
import * as monaco from 'monaco-editor';

monaco.editor.create(document.getElementById('container'), {
	value: ['function x() {', '\tconsole.log("Hello world!");', '}'].join('\n'),
	language: 'javascript'
});
  • webpack.config.js
js
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
const path = require('path');

module.exports = {
	entry: './index.js',
	output: {
		path: path.resolve(__dirname, 'dist'),
		filename: 'app.js'
	},
	module: {
		rules: [
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader']
			},
			{
				test: /\.ttf$/,
				use: ['file-loader']
			}
		]
	},
	plugins: [new MonacoWebpackPlugin()]
};

Option 2: Using plain webpack

Full working samples are available at https://github.com/microsoft/monaco-editor/tree/main/samples/browser-esm-webpack or https://github.com/microsoft/monaco-editor/tree/main/samples/browser-esm-webpack-small

  • index.js
js
import * as monaco from 'monaco-editor';

// Since packaging is done by you, you need
// to instruct the editor how you named the
// bundles that contain the web workers.
self.MonacoEnvironment = {
	getWorkerUrl: function (moduleId, label) {
		if (label === 'json') {
			return './json.worker.bundle.js';
		}
		if (label === 'css' || label === 'scss' || label === 'less') {
			return './css.worker.bundle.js';
		}
		if (label === 'html' || label === 'handlebars' || label === 'razor') {
			return './html.worker.bundle.js';
		}
		if (label === 'typescript' || label === 'javascript') {
			return './ts.worker.bundle.js';
		}
		return './editor.worker.bundle.js';
	}
};

monaco.editor.create(document.getElementById('container'), {
	value: ['function x() {', '\tconsole.log("Hello world!");', '}'].join('\n'),
	language: 'javascript'
});
  • webpack.config.js:
js
const path = require('path');

module.exports = {
	entry: {
		app: './index.js',
		// Package each language's worker and give these filenames in `getWorkerUrl`
		'editor.worker': 'monaco-editor/esm/vs/editor/editor.worker.js',
		'json.worker': 'monaco-editor/esm/vs/language/json/json.worker',
		'css.worker': 'monaco-editor/esm/vs/language/css/css.worker',
		'html.worker': 'monaco-editor/esm/vs/language/html/html.worker',
		'ts.worker': 'monaco-editor/esm/vs/language/typescript/ts.worker'
	},
	output: {
		globalObject: 'self',
		filename: '[name].bundle.js',
		path: path.resolve(__dirname, 'dist')
	},
	module: {
		rules: [
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader']
			},
			{
				test: /\.ttf$/,
				use: ['file-loader']
			}
		]
	}
};

Using parcel

A full working sample is available at https://github.com/microsoft/monaco-editor/tree/main/samples/browser-esm-parcel

When using parcel, we need to use the getWorkerUrl function and build the workers seperately from our main source. To simplify things, we can write a tiny bash script to build the workers for us.

  • index.js
js
import * as monaco from 'monaco-editor';

self.MonacoEnvironment = {
	getWorkerUrl: function (moduleId, label) {
		if (label === 'json') {
			return './json.worker.js';
		}
		if (label === 'css' || label === 'scss' || label === 'less') {
			return './css.worker.js';
		}
		if (label === 'html' || label === 'handlebars' || label === 'razor') {
			return './html.worker.js';
		}
		if (label === 'typescript' || label === 'javascript') {
			return './ts.worker.js';
		}
		return './editor.worker.js';
	}
};

monaco.editor.create(document.getElementById('container'), {
	value: ['function x() {', '\tconsole.log("Hello world!");', '}'].join('\n'),
	language: 'javascript'
});
  • build_workers.sh
sh
ROOT=$PWD/node_modules/monaco-editor/esm/vs
OPTS="--no-source-maps --log-level 1"        # Parcel options - See: https://parceljs.org/cli.html

parcel build $ROOT/language/json/json.worker.js $OPTS
parcel build $ROOT/language/css/css.worker.js $OPTS
parcel build $ROOT/language/html/html.worker.js $OPTS
parcel build $ROOT/language/typescript/ts.worker.js $OPTS
parcel build $ROOT/editor/editor.worker.js $OPTS

Then, simply run sh ./build_workers.sh && parcel index.html. This builds the workers into the same directory as your main bundle (usually ./dist). If you want to change the --out-dir of the workers, you must change the paths in index.js to reflect their new location.

note - the getWorkerUrl paths are relative to the build directory of your src bundle


Using Vite

Adding monaco editor to Vite is simple since it has built-in support for web workers. You only need to implement the getWorker function (NOT the getWorkerUrl) to use Vite's output (Source):

js
import * as monaco from 'monaco-editor';

self.MonacoEnvironment = {
	getWorker: function (workerId, label) {
		const getWorkerModule = (moduleUrl, label) => {
			return new Worker(self.MonacoEnvironment.getWorkerUrl(moduleUrl), {
				name: label,
				type: 'module'
			});
		};

		switch (label) {
			case 'json':
				return getWorkerModule('/monaco-editor/esm/vs/language/json/json.worker?worker', label);
			case 'css':
			case 'scss':
			case 'less':
				return getWorkerModule('/monaco-editor/esm/vs/language/css/css.worker?worker', label);
			case 'html':
			case 'handlebars':
			case 'razor':
				return getWorkerModule('/monaco-editor/esm/vs/language/html/html.worker?worker', label);
			case 'typescript':
			case 'javascript':
				return getWorkerModule('/monaco-editor/esm/vs/language/typescript/ts.worker?worker', label);
			default:
				return getWorkerModule('/monaco-editor/esm/vs/editor/editor.worker?worker', label);
		}
	}
};

monaco.editor.create(document.getElementById('container'), {
	value: "function hello() {\n\talert('Hello world!');\n}",
	language: 'javascript'
});

--- METRICS ---