The first step in everything is to download dependencies

npm install monaco-editor
Copy the code

“The gadget comes with a add-on that, don’t ask, simply do not know” (the editor seemed to have a bug)

monaco-editor-webpack-plugin
Copy the code

Once the dependencies are downloaded, they need to be configured

My project is packaged in Webpack, so it is configured in Webpack. The configuration method of vue-CLI project is different

Webpack configuration:

var MonacoWebpackPlugin = require("monaco-editor-webpack-plugin");

module.exports = merge(baseWebpackConfig, {
    ...
    plugins: [...new MonacoWebpackPlugin({
            languages: ["json"."typescript"."javascript"]})]});Copy the code

vue-cli

const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin')
 
module.exports = {
  chainWebpack: config= > {
    config.plugin('monaco-editor').use(MonacoWebpackPlugin, [
      {
        // Languages are loaded on demand at runtime
        languages: ['json'.'javascript'.'html'.'xml']}])}}Copy the code

The next step is to encapsulate it as a component

<template> <div id="monaco-editor-box"> <div id="monaco-editor" ref="monacoEditor" /> </div> </template> <script> import  * as monaco from "monaco-editor/esm/vs/editor/editor.main"; export default { components: {}, props: { editorOptions: { type: Object, default: Function () {return {selectOnLineNumbers: true, roundedSelection: false, readOnly: true, // readOnly cursorStyle: "Line ", // cursor style automaticLayout: false, // automaticLayout glyphMargin: true, // font edge useTabStops: false, fontSize: 28, // font size autoIndent: true, // automatic layout //quickSuggestionsDelay: 500, // code prompt delay}; }, codes: {type: String, default: function () {return "<div> please edit HTML content </div>"; },},}, data() {return {editor: null, // text editor isSave: true, // codeValue: null, // saved text}; }, mounted() { this.initEditor(); }, methods: { initEditor() { const self = this; // Initialize the editor to make sure the dom has rendered this.editor = monaco.editor. Create (self.$refs.monacoEditor, {value: Self. CodeValue | | self. Codes, / / initial display content editor language: "javascript", / / support theme: "v - dark, / / theme selectOnLineNumbers: True, // Display line number editorOptions: self.editorOptions,}); // self.$emit("onMounted", self.editor); / / editor to create complete callback / / self. The editor. OnDidChangeModelContent (function (event) {/ / / / editor contents changge event / / self. CodesCopy = self.editor.getValue(); // self.$emit("onCodeChange", self.editor.getValue(), event); / /}); ,}}}; </script> <style scoped> #monaco-editor { height: 600px; } </style>Copy the code

Finally, component references are omitted from the examples

The problem record

One of the problems was:

My solution is to add a typescript language type to the WebPack configuration, so it doesn’t necessarily work in other scenarios

If there is a better solution, welcome to exchange