Skip to content

Instantly share code, notes, and snippets.

@ezzabuzaid
Last active May 3, 2023 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezzabuzaid/8e062d7830cd0e422d71aedc79268e9b to your computer and use it in GitHub Desktop.
Save ezzabuzaid/8e062d7830cd0e422d71aedc79268e9b to your computer and use it in GitHub Desktop.

I was able to use the ESM version with Angular 15 following these steps:

Note: I use nx, but it should work with other executers like Angular builder

  1. install monaco-editor-webpack-plugin
  2. change the build target to use an executer that supports modifying the webpack config. in case of nx 16, use "@nx/angular:webpack-browser"
  3. add webpack.config.js

angular.json/project.json

{
  "build": {
    "executor": "@nx/angular:webpack-browser",
    "outputs": ["{options.outputPath}"],
    "options": {
      "customWebpackConfig": {
        "path": "path/to/webpack.config.js"
      },
      ...rest of the options
   }
}

webpack.config.js

const path = require('path');
const MONACO_DIR = path.resolve(process.cwd(), 'node_modules/monaco-editor');
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = {
  plugins: [new MonacoWebpackPlugin()],
  module: {
    rules: [
      {
        test: /\.ttf$/,
        include: MONACO_DIR,
        use: ['file-loader'],
      },
      {
        test: /\.css$/,
        include: MONACO_DIR,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
};

now, you might create a directive to instantiate the editor

@Directive({
  standalone: true,
  selector: '[codeEditor]',
})
export class EditorDirective {
  editor?: editor.IStandaloneCodeEditor;
  hostEl = inject(ElementRef).nativeElement;
  constructor() {
    import('monaco-editor/esm/vs/editor/editor.api').then(({ editor }) => {
      this.editor = editor.create(this.hostEl, {
        value: 'function hello() {\n\tconsole.log("Hello, world!");\n}',
        language: 'typescript',
        autoIndent: 'full',
        readOnly: true,
        domReadOnly: true,
      });
    });
  }
}
@Component({
  standalone: true,
  template: `<div codeEditor style="width: 100%; height: 100%"></div>`,
  styles: [`:host{display: block; width: 100%; height: 100%}`]
  imports: [EditorDirective],
})
export class YourComponent {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment