vue3+vite+pnpm项目 使用monaco-editor常见问题

文章目录

    • 一、使用步骤
      • [1.1 安装插件](#1.1 安装插件)
      • [1.2 配置 vite.config.js](#1.2 配置 vite.config.js)
      • [1.3 封装 json-editor 组件](#1.3 封装 json-editor 组件)
      • [1.4 使用 json-editor 组件](#1.4 使用 json-editor 组件)
    • 二、遇到报错
      • [2.1 `TypeError: Cannot read properties of undefined (reading 'toUrl')`](#2.1 TypeError: Cannot read properties of undefined (reading 'toUrl'))
      • [2.2 `Cannot read properties of undefined (reading 'languageWorkers')`](#2.2 Cannot read properties of undefined (reading 'languageWorkers'))
    • 参考地址

一、使用步骤

Monaco Editor API

1.1 安装插件

shell 复制代码
pnpm install monaco-editor --save
pnpm install monaco-editor-webpack-plugin --save 
pnpm install --save-dev vite-plugin-monaco-editor

1.2 配置 vite.config.js

js 复制代码
import monacoEditorPlugin from 'vite-plugin-monaco-editor';

export default defineConfig({
	...
	 plugins: [
        monacoEditorPlugin({}),
    ],
	...
})

1.3 封装 json-editor 组件

html 复制代码
/* 模块名称:json-editor */
<template>
  <div ref="monacoDom" class="json-editor"></div>
</template>
<script lang="ts" setup>
import beautify from 'js-beautify'
import * as monaco from 'monaco-editor';

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  readOnly: {
    type: Boolean,
    default: false,
  },
  config: {
    type: Object,
    default() {
      return {};
    }
  }
});
const emits = defineEmits(['update:modelValue', 'change', 'ready'])
const monacoDom: Ref<HTMLElement | null> = ref(null);
let monacoInstance: monaco.editor.IStandaloneCodeEditor | null = null;

watch(() => props.modelValue, (newValue) => {
  const value = monacoInstance?.getValue();
  if (newValue !== value) {
    monacoInstance?.setValue(props.modelValue)
  }
})
watch(() => props.readOnly, (readOnly) => {
  monacoInstance?.updateOptions({
    readOnly,
  });
})
onMounted(() => {
  monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
    allowComments: true,
    validate: true,
    trailingCommas: 'ignore',
    schemaValidation: 'warning'
  })
  monaco.languages.json.jsonDefaults.setModeConfiguration({
    completionItems: false,
    tokens: true,
    colors: true,
    foldingRanges: true,
    diagnostics: true,
  })
  monacoInstance = monaco.editor.create(monacoDom.value as HTMLElement, {
    value: props.modelValue,
    language: 'json',
    automaticLayout: true,
    parameterHints: {
      enabled: true
    },
    minimap: {
      enabled: false,
    },
    wrappingStrategy: 'advanced',
    scrollBeyondLastLine: false,
    overviewRulerLanes: 0,
    scrollbar: {
      alwaysConsumeMouseWheel: false
    },
    hover: {
      enabled: true,
      above: false,
    },
    renderLineHighlight: 'none',
    fontSize: 14,
    readOnly: props.readOnly,
    ...props.config
  })
  monacoInstance.onDidChangeModelContent(() => {
    emits('update:modelValue', monacoInstance?.getValue())
    emits('change', monacoInstance?.getValue())
  })
  emits('ready')
})
onActivated(() => {
  monacoInstance?.focus()
})
onBeforeUnmount(() => {
  monacoInstance?.dispose();
})
const format = () => {
  const formatStr = beautify(props.modelValue, { indent_size: 4 });
  monacoInstance?.setValue(formatStr)
}
const focus = () => {
  monacoInstance?.focus()
}
defineExpose({
  format,
  focus
});
</script>
<style lang="scss">
.json-editor {
  width: 100%;
  height: 100%;
}
</style>

1.4 使用 json-editor 组件

html 复制代码
<template>
  <json-editor
    ref="jsonComponents"
    :model-value="strJson"
    @update:model-value="handleChangeResponseJson"
  />
</template>
<script lang="ts" setup>
import JsonEditor from '../common/json-editor.vue'

const jsonComponents: Ref<null | { format: () => void }[]> = ref(null)
const strJson = ref('')

//更改返回json数据
const handleChangeResponseJson = (value: string) => {
 // 返回内容值,根据业务增加后面的逻辑
}
</script>

二、遇到报错

2.1 TypeError: Cannot read properties of undefined (reading 'toUrl')

出现上面的报错的原因是只安装了 monaco-editor 插件,未对模块加载配置,需安装对应的解析器 monaco-editor-webpack-pluginvite-plugin-monaco-editor

2.2 Cannot read properties of undefined (reading 'languageWorkers')

出现上面的报错的原因是 在 vite.config.js 配置 monacoEditorPlugin() 时,需要传默认值,monacoEditorPlugin({})

参考地址

https://blog.csdn.net/qq_37772059/article/details/125404159

相关推荐
dualven_in_csdn1 小时前
搞了两天的win7批处理脚本问题
java·linux·前端
你的人类朋友1 小时前
✍️【Node.js程序员】的数据库【索引优化】指南
前端·javascript·后端
小超爱编程2 小时前
纯前端做图片压缩
开发语言·前端·javascript
应巅2 小时前
echarts 数据大屏(无UI设计 极简洁版)
前端·ui·echarts
萌萌哒草头将军3 小时前
🚀🚀🚀什么?浏览器也能修改项目源文件了?Chrome 团队开源的超强 Vite 插件!🚀🚀🚀
vue.js·react.js·vite
Jimmy3 小时前
CSS 实现描边文字效果
前端·css·html
islandzzzz3 小时前
HMTL+CSS+JS-新手小白循序渐进案例入门
前端·javascript·css·html
Senar3 小时前
网页中如何判断用户是否处于闲置状态
前端·javascript
很甜的西瓜4 小时前
typescript软渲染实现类似canvas的2d矢量图形引擎
前端·javascript·typescript·图形渲染·canvas
Allen Bright4 小时前
【CSS-9】深入理解CSS字体图标:原理、优势与最佳实践
前端·css