如何在Angular 8中为CodeMirror添加Simple Mode自定义模式
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
keywordregex to include terms specific to your DSL (e.g.,regex: /(?:myCustomCommand|anotherTerm)\b/, token: "keyword"). - Adjust Token Styles: Change
tokenvalues (like "variable-2", "atom") to control how different elements are highlighted. - Add New Rules: Insert new regex entries in the
startarray to handle unique syntax (e.g., custom literals, operators, or comment styles). - Modify Comment Rules: Update the
lineCommentmeta 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

