强大的代码编辑器组件,你知道几个?

开发 前端
通过本文,您应该已经了解了如何在网页中使用CodeMirror实现代码编辑与高亮。当然,CodeMirror还有很多高级特性等待您去发掘。希望本文能帮助您更好地使用CodeMirror,为您的Web开发带来更多便利。

上次介绍了一个简单的示例,基于javascript如何从一段文本解析为一段代码,今天我们看下一下个功能类似,但非常强大的代码编辑器组件 

CodeMirror

CodeMirror https://codemirror.net/

在Web开发中,我们经常需要在网页上展示代码,或者让用户直接在网页上编写代码。为了提高用户体验,我们通常会使用代码编辑器来实现代码的高亮、自动补全等功能。而在众多代码编辑器中,CodeMirror无疑是一个功能强大、易用的选项。本文将带您深入了解CodeMirror的基本用法和高级特性,让您能够轻松地在网页中实现代码编辑与高亮。

什么是CodeMirror?

CodeMirror是一个基于JavaScript的代码编辑器,它可以在网页中实现代码的高亮、自动补全等功能。CodeMirror支持多种编程语言,如JavaScript、HTML、CSS、Python等,并且可以通过插件扩展支持更多的语言。CodeMirror的使用非常简单,只需要引入相应的库文件,然后通过简单的配置即可实现代码编辑与高亮。

如何使用CodeMirror?

基于webpack

  1. 初始化项目
npm init -y
  1. 引入库文件
npm i codemirror @codemirror/lang-javascript 

npm i -D webpack webpack-cli webpack-dev-server 

npm i -D css-loader scss scss-loader style-loader html-loader html-webpack-plugin
  1. 创建编辑器
<div id="app">

</div>
  1. 初始化Codemirror
const state = EditorState.create({
    doc: 'console.log("hello codemirror")',
    extensions: [
        basicSetup,
        javascript(),
        // 其他扩展,包括主题、语法高亮...
    ],
});

const editor = new EditorView({
    state,
    parent: document.getElementById("editor")
})
  1. 配置webpack
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/js/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  devServer: {
    static: {
      directory: path.join(__dirname, 'dist'),
      watch: true,
    },
    compress: true,
    port: 9000,
    hot: true, // 启用HMR
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
    }),
    new webpack.HotModuleReplacementPlugin(),
  ],
  optimization: {
    minimize: false, // 关闭代码压缩
  },
  module: {
    rules: [
      {
        test: /\.scss$/, // 正则表达式,匹配所有 .scss 文件
        use: [
          'style-loader', // 将 JS 字符串生成为 style 节点
          'css-loader', // 将 CSS 转化成 CommonJS 模块
          'sass-loader' // 将 Sass 编译成 CSS,需要 npm 安装 sass-loader 和 sass
        ]
      },
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      },
      {
        test: /\.html$/i,
        loader: 'html-loader',
      },
    ],
  },
  mode: 'development',
};
  1. 启动
{
    "scripts": {
      "start": "webpack serve --open",
      "build": "webpack --mode=dependencies"
    },
}
npm start

CodeMirror的高级特性

  1. 自定义主题

CodeMirror允许我们自定义主题,以实现个性化的代码高亮效果。可以通过以下方式设置自定义主题:

import {EditorView} from "@codemirror/view"

let myTheme = EditorView.theme({
  "&": {
    color: "white",
    backgroundColor: "#034"
  },
  ".cm-content": {
    caretColor: "#0e9"
  },
  "&.cm-focused .cm-cursor": {
    borderLeftColor: "#0e9"
  },
  "&.cm-focused .cm-selectionBackground, ::selection": {
    backgroundColor: "#074"
  },
  ".cm-gutters": {
    backgroundColor: "#045",
    color: "#ddd",
    border: "none"
  }
}, {dark: true})
  1. 自定义语言模式

除了内置的语言模式外,我们还可以自定义语言模式。首先需要引入相应的模式文件,然后通过以下方式设置自定义语言模式:模板是基于lezer解析,syntax.grammar,基于lezer的语法解析器,可以自定义语法规则,实现自定义语言模式,像之前那样逐个对字符处理。

@top Program { expression* }

@skip { space | LineComment }

expression {
  Identifier |
  String |
  Boolean |
  Application { "(" expression* ")" }
}

@tokens {
  Identifier { $[a-zA-Z_\-0-9]+ }

  String { '"' (!["\\] | "\\" _)* '"' }

  Boolean { "#t" | "#f" }

  LineComment { ";" ![\n]* }

  space { $[ \t\n\r]+ }

  "(" ")"
}

@detectDelim
import {parser} from "./syntax.grammar"
import {LRLanguage, LanguageSupport, indentNodeProp, foldNodeProp, foldInside, delimitedIndent} from "@codemirror/language"
import {styleTags, tags as t} from "@lezer/highlight"

export const EXAMPLELanguage = LRLanguage.define({
  parser: parser.configure({
    props: [
      indentNodeProp.add({
        Application: delimitedIndent({closing: ")", align: false})
      }),
      foldNodeProp.add({
        Application: foldInside
      }),
      styleTags({
        Identifier: t.variableName,
        Boolean: t.bool,
        String: t.string,
        LineComment: t.lineComment,
        "( )": t.paren
      })
    ]
  }),
  languageData: {
    commentTokens: {line: ";"}
  }
})

export function EXAMPLE() {
  return new LanguageSupport(EXAMPLELanguage)
}
  1. 语法高亮

可以根据标签类型设置不同标签的颜色与其他样式,可以根据内置的tag类型定义不同的显示风格:

import {tags} from "@lezer/highlight"
import {HighlightStyle} from "@codemirror/language"

const myHighlightStyle = HighlightStyle.define([
  {tag: tags.keyword, color: "#fc6"},
  {tag: tags.comment, color: "#f5d", fontStyle: "italic"}
])

codemirror的扩展点很多,类似于Visual Studio Code的Web版本都可以基于该框架试下,在官网上罗列了具体的:

Accessibility

Works well with screen readers and keyboard-only users.

Mobile Support

Use the platform's native selection and editing features on phones.

Bidirectional Text

Support mixing of right-to-left and left-to-right text.

Syntax Highlighting

Color code to reflect syntactic structure.

Line Numbers

Display gutters with line numbers or other information next to the code.

Autocompletion

Provide language-specific completion hints in the editor.

Code Folding

Temporarily hide parts of the document.

Search/Replace

Editor-specific search, regexp search, and replace functionality.

Full Parsing

Detailed parse trees allow many types of language integration.

Extension Interface

Robustly implement demanding editor extensions.

Modularity

Most features are implemented on top of a generic public API.

Speed

Remains responsive even on huge documents and long lines.

Bracket Closing

Automatically insert matching brackets during typing.

Linting

Show error and warning messages in the editor.

Flexible Styling

Mix font styles and sizes, add widgets in the content.

Theming

Import or create custom visual editor styles.

Collaborative Editing

Allow multiple users to edit the same document.

Undo History

Undo and redo functionality with collab editing support.

Multiple Selections

Select and edit multiple ranges of the document at once.

Internationalization

Provide custom text to display or announce to the user.

...and more

Find a full description of the library's features in the docs.

结束语

以上就是关于CodeMirror的简单介绍和基本用法。通过本文,您应该已经了解了如何在网页中使用CodeMirror实现代码编辑与高亮。当然,CodeMirror还有很多高级特性等待您去发掘。希望本文能帮助您更好地使用CodeMirror,为您的Web开发带来更多便利。

责任编辑:武晓燕 来源: Java技术指北
相关推荐

2017-01-18 17:00:35

编辑器

2021-02-24 11:13:48

IDE工具代码编辑器

2019-11-27 10:27:22

程序员Git脚本语言

2021-08-12 18:51:02

Python

2022-03-20 18:12:03

Shotcut开源视频编辑器

2020-04-23 16:04:25

代码编辑器工具程序员

2009-12-01 16:44:06

PHP编辑器

2019-06-10 11:06:04

JavaScript编辑器HTML5

2009-06-11 10:03:57

NetBeans代码

2022-09-08 09:01:41

CodePenJavaScripCSS

2021-10-26 10:30:31

代码编辑器LinuxVS Code

2015-02-12 09:51:24

代码编辑

2021-03-10 09:15:15

代码文本编辑器编程

2022-03-03 20:57:53

代码编辑器VS code

2024-02-28 16:26:14

Linuxvi编辑器

2020-07-15 15:12:17

Python代码编辑器编程语言

2011-10-31 10:17:05

插件

2017-03-09 19:25:38

JavaScript代码编辑器

2020-03-25 14:16:58

文本编辑器语言开发

2011-01-10 16:17:49

点赞
收藏

51CTO技术栈公众号