如何为Nuxt.js 2配置AMD版Monaco Editor
在Nuxt.js 2中集成最新AMD版Monaco Editor
1. 安装依赖
首先安装核心包及配套webpack插件:
npm install monaco-editor --save npm install monaco-editor-webpack-plugin worker-loader --save-dev
2. 配置Nuxt.js的webpack
在项目根目录的nuxt.config.js中修改配置:
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin') export default { // ...其他原有配置 build: { plugins: [ new MonacoWebpackPlugin({ // 按需指定加载的语言和功能,减少打包体积 languages: ['javascript', 'typescript', 'html', 'css'], features: ['coreCommands', 'find', 'format'] }) ], extend(config, { isClient }) { if (isClient) { // 处理Monaco的worker文件 config.module.rules.push({ test: /\.worker\.js$/, use: { loader: 'worker-loader' } }) } } } }
3. 封装Monaco Editor组件
在components目录下创建MonacoEditor.vue:
<template> <div ref="editorWrapper" class="monaco-editor-box"></div> </template> <script> export default { props: { value: { type: String, default: '' }, language: { type: String, default: 'javascript' }, theme: { type: String, default: 'vs-dark' } }, data() { return { editorInstance: null } }, mounted() { // 动态导入Monaco,避免首屏加载过重 import('monaco-editor').then((monaco) => { this.editorInstance = monaco.editor.create(this.$refs.editorWrapper, { value: this.value, language: this.language, theme: this.theme, automaticLayout: true, minimap: { enabled: false } }) // 监听内容变化,同步到父组件 this.editorInstance.onDidChangeModelContent(() => { this.$emit('input', this.editorInstance.getValue()) }) }) }, beforeDestroy() { // 销毁实例,避免内存泄漏 if (this.editorInstance) { this.editorInstance.dispose() } }, watch: { value(newVal) { if (this.editorInstance && this.editorInstance.getValue() !== newVal) { this.editorInstance.setValue(newVal) } }, language(newVal) { if (this.editorInstance) { window.monaco.editor.setModelLanguage(this.editorInstance.getModel(), newVal) } } } } </script> <style scoped> .monaco-editor-box { width: 100%; height: 600px; border-radius: 4px; overflow: hidden; } </style>
4. 在页面中使用组件
在目标页面(比如pages/index.vue)中引入并使用:
<template> <div class="editor-page"> <h2>代码编辑器</h2> <MonacoEditor v-model="code" language="javascript" /> </div> </template> <script> import MonacoEditor from '@/components/MonacoEditor.vue' export default { components: { MonacoEditor }, data() { return { code: '// 开始编写你的代码\nfunction hello() {\n console.log("Hello Monaco!")\n}' } } } </script> <style scoped> .editor-page { padding: 20px; } </style>
常见问题处理
- 若打包时出现路径错误,可在
MonacoWebpackPlugin中添加publicPath: '/_nuxt/monaco/'参数 - 编辑器样式异常时,确保
automaticLayout已开启且容器有明确宽高
内容的提问来源于stack exchange,提问作者Edward
相关产品推荐
相关产品推荐

