ACE editor - allow custom modes and themes in Angular/TypeScript

Viewed 394

Introduction:

I've an Angular application where custom SQL statements can be written by using the ACE editor (https://ace.c9.io/). Even though there are modes and themes for SQL, I wanted to create a custom mode and a custom theme for my requirements.


Setup:

I followed this tutorial: https://blog.shhdharmen.me/how-to-setup-ace-editor-in-angular

  • ng new ace-app (Angular 13.3.2)
  • npm install ace-builds (ACE-Builds 1.4.14)

component.ts

import * as ace from 'ace-builds';

...

public aceEditor: ace.Ace.Editor;

@ViewChild('editor') private editor!: ElementRef<HTMLElement>;

...

  ngAfterViewInit(): void {
    // I don't understand why we don't set the "basePath" to our installed package
    ace.config.set('basePath', 'https://unpkg.com/ace-builds@1.4.12/src-noconflict');

    this.aceEditor = ace.edit(this.editor.nativeElement);

    if (this.aceEditor) {
      this.aceEditor.setOptions({
        mode: 'ace/mode/sql',
        theme: 'ace/theme/sqlserver',
      });
    }

component.html

<div #editor></div>

Result:

The editor is working, but now I need to somehow add a custom mode and theme.

ACE editor box with sql statement


Problems and Questions:

  • Is it correct to set the basePath to an external URL if I've the package already installed (obsolete due to Edit 1)?
  • How and where would I add the custom mode.js and theme.js?
  • How can I direct ace to the custom mode.js and theme.js?

Edit 1:

I managed to get rid of this line of code:

ace.config.set('basePath', 'https://unpkg.com/ace-builds@1.4.12/src-noconflict');

by directly importing the theme and mode with:

import 'ace-builds/src-noconflict/mode-sql';
import 'ace-builds/src-noconflict/theme-sqlserver';

the rest of the code did not have to be changed.

1 Answers

After looking through several projects and issues, I figured out that the best way to implement custom themes and modes for the ACE editor is to copy existing ones from ./node-modules/ace-builds/src-conflict and paste them to ./src/assets/ace.

Example:

Copy an existing mode (and optionally the theme) that represents your required syntax highlighting the most, in my case it was mode-sql.js. I copied the files to ./src/assets/ace and changed the import in my component.ts from:

import 'ace-builds/src-noconflict/mode-sql';
import 'ace-builds/src-noconflict/theme-sqlserver';

To:

import '../../../../assets/ace/mode-sql.js';
import '../../../../assets/ace/theme-sqlserver.js';

Everything else was kept exactly as described in the initial question. From there you can start to change the name of mode and theme, update the rules as well as the styling according to your requirements.

Related