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

如何在Angular 8中为CodeMirror添加Simple Mode自定义模式

Integrating CodeMirror Simple Mode into Angular 8 with @ctrl/ngx-codemirror

Let's walk through how to integrate the CodeMirror Simple Mode example into your Angular 8 project, then customize it for your own DSL. Here's a step-by-step guide:

1. Install Required Dependencies

First, make sure you have the necessary packages installed. Run this command in your project root:

npm install @ctrl/ngx-codemirror codemirror --save

2. Import the CodeMirror Module in Your AppModule

Open app.module.ts and add the NgxCodemirrorModule (along with FormsModule for ngModel support) to your imports array:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { NgxCodemirrorModule } from '@ctrl/ngx-codemirror';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, FormsModule, NgxCodemirrorModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

3. Add CodeMirror Styles

To ensure the editor renders correctly, include CodeMirror's base CSS in your project. You can add this to your angular.json under the styles array:

"styles": [
  "src/styles.css",
  "node_modules/codemirror/lib/codemirror.css"
]

Or import it directly in your styles.css:

@import '~codemirror/lib/codemirror.css';

4. Define the Simple Mode in Your Component

Open app.component.ts and import CodeMirror along with the Simple Mode framework. Then define your custom mode in the ngOnInit lifecycle hook:

import { Component, OnInit } from '@angular/core';
import * as CodeMirror from 'codemirror';
import 'codemirror/mode/simple/simple.js'; // Load the Simple Mode base

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  // Initial sample code to test the mode
  code = `// Test your syntax here
function calculateTotal() {
  var total = 0;
  if (items.length > 0) {
    return total + items.reduce((a,b) => a+b);
  }
}`;
  
  // CodeMirror configuration options
  options: CodeMirror.EditorConfiguration = {
    mode: 'simplemode', // Matches the mode name we'll define
    lineNumbers: true,
    indentUnit: 2,
    theme: 'default' // Swap for themes like 'monokai' if you install them
  };

  ngOnInit(): void {
    // Paste the Simple Mode definition from the CodeMirror example
    CodeMirror.defineSimpleMode("simplemode", {
      // Start state with initial highlighting rules
      start: [
        { regex: /"(?:[^\\]|\\.)*?(?:"|$)/, token: "string" },
        { regex: /(function)(\s+)([a-z$][\w$]*)/, token: ["keyword", null, "variable-2"] },
        { regex: /(?:function|var|return|if|for|while|else|do|this)\b/, token: "keyword" },
        { regex: /true|false|null|undefined/, token: "atom" },
        { regex: /0x[a-f\d]+|[-+]?(?:\.\d+|\d+\.?\d*)(?:e[-+]?\d+)?/i, token: "number" },
        { regex: /\/\/.*/, token: "comment" },
        { regex: /\/(?:[^\\]|\\.)*?\//, token: "variable-3" },
        { regex: /\/\*/, token: "comment", next: "comment" },
        { regex: /[-+\/*=&<>!]+/, token: "operator" },
        { regex: /[\{\[\(]/, indent: true },
        { regex: /[\}\]\)]/, dedent: true },
        { regex: /[a-z$][\w$]*/, token: "variable" },
        { regex: /<<<\/?/, token: "meta", mode: { spec: "xml", end: />>/ } }
      ],
      // Multi-line comment state
      comment: [
        { regex: /.*?\*\//, token: "comment", next: "start" },
        { regex: /.*/, token: "comment" }
      ],
      // Global mode settings
      meta: {
        dontIndentStates: ["comment"],
        lineComment: "//"
      }
    });
  }
}

5. Customize the Mode for Your DSL

Now you can tweak the mode rules to match your own syntax:

  • Update Keywords: Modify the keyword regex to include terms specific to your DSL (e.g., regex: /(?:myCustomCommand|anotherTerm)\b/, token: "keyword").
  • Adjust Token Styles: Change token values (like "variable-2", "atom") to control how different elements are highlighted.
  • Add New Rules: Insert new regex entries in the start array to handle unique syntax (e.g., custom literals, operators, or comment styles).
  • Modify Comment Rules: Update the lineComment meta property or comment regex patterns if your DSL uses different comment syntax.

6. Verify Your Template

Your existing app.component.html is already correctly set up, but double-check:

<ngx-codemirror [(ngModel)]="code" [options]="options"></ngx-codemirror>

Run your Angular app with ng serve and you’ll see the CodeMirror editor with your custom Simple Mode applied. You can now refine the rules to perfectly match your DSL’s syntax.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 20:43:10