You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:在ASP.Net Core应用中配置CodeMirror 6的可行起步方案

CodeMirror v6 可扩展起步模板搭建

基础依赖安装

确保已初始化npm项目(无则执行npm init -y),安装核心依赖:

npm install @codemirror/view @codemirror/state @codemirror/lang-javascript

项目文件结构

├── index.html
├── main.js
└── package.json

核心代码实现

index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>CodeMirror 6 起步模板</title>
  <style>
    body { margin: 0; }
    .cm-editor { height: 100vh; font-size: 16px; }
  </style>
</head>
<body>
  <div id="editor"></div>
  <script type="module" src="./main.js"></script>
</body>
</html>

main.js

import { EditorState } from '@codemirror/state';
import { EditorView, lineNumbers, highlightActiveLineGutter, highlightSpecialChars, drawSelection, dropCursor, rectangularSelection, crosshairCursor, highlightActiveLine } from '@codemirror/view';
import { javascript } from '@codemirror/lang-javascript';
import { defaultKeymap } from '@codemirror/commands';
import { bracketMatching } from '@codemirror/language';
import { searchKeymap } from '@codemirror/search';
import { closeBrackets, closeBracketsKeymap } from '@codemirror/closebrackets';
import { autocompletion, completionKeymap } from '@codemirror/autocomplete';
import { lintKeymap } from '@codemirror/lint';

// 自定义行装饰示例(对应你尝试的装饰功能)
const oddLineHighlight = EditorView.baseTheme({
  '.cm-line:nth-child(odd)': {
    backgroundColor: '#f8f8f8'
  }
});

// 可扩展的基础配置集合
const basicExtensions = [
  // 基础编辑器功能
  lineNumbers(),
  highlightActiveLineGutter(),
  highlightSpecialChars(),
  drawSelection(),
  dropCursor(),
  rectangularSelection(),
  crosshairCursor(),
  highlightActiveLine(),
  // 语言与语法相关
  bracketMatching(),
  closeBrackets(),
  javascript(),
  // 交互增强
  autocompletion(),
  // 自定义装饰
  oddLineHighlight,
  // 基础配置
  EditorState.tabSize.of(2),
  EditorView.contentAttributes.of({ spellcheck: 'false' }),
  // 编辑器样式
  EditorView.theme({
    '&': { height: '100%' },
    '.cm-content': { padding: '12px' }
  }),
  // 快捷键集合
  EditorState.keyMap.of([
    ...defaultKeymap,
    ...searchKeymap,
    ...closeBracketsKeymap,
    ...completionKeymap,
    ...lintKeymap
  ])
];

// 初始化编辑器
new EditorView({
  state: EditorState.create({
    doc: `// CodeMirror 6 可扩展起步模板
// 奇数行已添加背景装饰,可自由扩展功能
function demo() {
  const message = "Hello CodeMirror!";
  console.log(message);
}
`,
    extensions: basicExtensions
  }),
  parent: document.getElementById('editor')
});

运行方式

  1. 启动本地静态服务器(如npx serve .),访问index.html即可看到效果
  2. 如需打包,可使用esbuild:
    npx esbuild main.js --bundle --outfile=dist.js
    
    之后将html中的脚本引入改为dist.js即可

扩展说明

所有功能都通过向basicExtensions数组添加新的Extension实现,比如要添加更复杂的文本装饰,只需参照官方示例封装对应的扩展模块,加入数组即可。

内容的提问来源于stack exchange,提问作者Geert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 05:25:44