目录
安装 monaco-editor-esm-webpack-plugin
为什么要集成Monaco Editor
Monaco Editor是微软开源的一款网页版的vscode编辑器,风格、操作方式几乎与vscode一致,Github地址:https://github.com/microsoft/monaco-editor 。 由于项目中需要开发一个sql语句编辑器的功能,故采用monaco editor的解决方案。
开始使用
安装monaco-editor
npm install monaco-editor --save
集成至页面
页面上添加一个div:
<div id="monaco-editor">
</div>
初始化monaco编辑器
import * as monaco from 'monaco-editor'
this.editor = monaco.editor.create(document.getElementById('monoco-editor'), {
value: '',
language: 'sql',
automaticLayout: true
})
按照以上操作后,页面即可集成monaco editor功能。
右键菜单增加自定义操作
需要调用addAction方法,文档:https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.istandalonecodeeditor.html#addaction ,实例代码如下:
this.editor.addAction({
id: 'file_formatter',
label: '格式化文档', // 菜单名称
keybindings: [monaco.KeyMod.Shift | monaco.KeyMod.Alt | monaco.KeyCode.KEY_F], // 快捷键
contextMenuGroupId: 'code_formatter',
run: () => {
// const content = this.editor.getValue()
// this.editor.setValue(format(content, { indent: ' ' }))
// TODO 添加格式化操作
}
})
最终效果
本地化i18n
本地化采用monaco-editor-esm-webpack-plugin方式实现,Github地址:https://github.com/wang12124468/monaco-editor-esm-webpack-plugin 。
安装 monaco-editor-esm-webpack-plugin
npm install monaco-editor-esm-webpack-plugin --save-dev
安装 monaco-editor-nls
npm install monaco-editor-webpack-plugin monaco-editor-nls --save
修改 webpack.config.js
const MonacoWebpackPlugin = require('monaco-editor-esm-webpack-plugin');
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.js'
},
module: {
rules: [
{
test: /\.js/,
enforce: 'pre',
include: /node_modules[\\\/]monaco-editor[\\\/]esm/,
use: MonacoWebpackPlugin.loader
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [
new MonacoWebpackPlugin()
]
};
设置中文
import { setLocaleData } from 'monaco-editor-nls';
import zh_CN from 'monaco-editor-nls/locale/zh-hans';
// You must import/require after `setLocaleData`
setLocaleData(zh_CN);
import * as monaco from 'monaco-editor'
this.editor = monaco.editor.create(document.getElementById('monoco-editor'), {
value: '',
language: 'sql',
automaticLayout: true
})
最终效果
以上