npm install monaco-editor@0.32.1
main.js设置下面:
import mcommon from '@/components/commons'
Vue.use(mcommon)
vue.config.js设置下面:
const MonacoWebpackPlugin = require('monaco-editor-esm-webpack-plugin');
configureWebpack: {
module: {
rules: [{
test: /\.js/,
enforce: 'pre',
include: /node_modules[\\\/]monaco-editor[\\\/]esm/,
use: MonacoWebpackPlugin.loader
}]
},
plugins: [
new MonacoWebpackPlugin()
]
}
页面用法
<div style="margin-top:10px;">
<editor :code="code" height="300px" ref="formula" lib='123'/>
</div>
import editor from '@/components/monaco/formulaEditor'
components: {
editor
},
handleNodeClick(data) { // 往编辑器里插入内容
console.log(data);
this.$refs.formula.insertCode(data.label);
}
下面是模仿vscode编辑器都editor组件
<template>
<div class="myEditor">
<div id="container" ref="container" :style="'height:' + height"></div>
</div>
</template>
<script>
import { setLocaleData } from "monaco-editor-nls";
import zh_CN from "monaco-editor-nls/locale/zh-hans";
setLocaleData(zh_CN);
const monaco = require("monaco-editor/esm/vs/editor/editor.api");
import formulajs from "../../assets/formulajs/formulajs.type";
var editor;
export default {
props: {
code: {
type: String,
required: true,
},
lib: {
type: String,
required: true,
},
height: {
type: String,
required: true,
},
},
data() {
return {
editor,
};
},
mounted() {
let _this = this;
// extra libraries
monaco.languages.typescript.typescriptDefaults.addExtraLib(
formulajs,
"ts:filename/formulajs.d.ts"
);
var libUri1 = "ts:filename/bill.d.ts";
monaco.languages.typescript.typescriptDefaults.addExtraLib(
_this.lib,
libUri1
);
editor = monaco.editor.create(document.getElementById("container"), {
language: "typescript",
value: _this.code,
});
},
methods: {
getValue: () => {
let val = editor.getValue();
console.warn(val);
eval(val);
},
insertCode: (val) => {
let selection = editor.getSelection();
let range = new monaco.Range(
selection.startLineNumber,
selection.startColumn,
selection.endLineNumber,
selection.endColumn
);
let id = { major: 1, minor: 1 };
let op = {
identifier: id,
range: range,
text: val,
forceMoveMarkers: true,
};
editor.executeEdits("my-source", [op]);
},
},
};
</script>
<style scoped>
#container {
height: 100%;
text-align: left;
}
</style>