Posted 18 days ago. Visible to the public.

How to: Use Ace editor in a Webpack project

The Ace editor is a great enhancement when you want users to supply some kind of code (HTML, JavaScript, Ruby, etc).
It offers syntax highlighting and some neat features like auto-indenting.

Integrating it with Webpack as described in the documentation – by using ace-builds and ace-builds/webpack-resolver – failed pretty hard for me. Maybe because Rails' Webpacker is still on Webpack 2.
The following works for Ruby on Rails with Webpacker / Webpack 2.

  1. Do not use the ace-builds NPM package, because you won't be able to load it properly. Instead, use brace:

    Copy
    yarn add brace
  2. You can then import and use ace, mode configuration, and styles like so:

    Copy
    import ace from 'brace' import 'brace/mode/html' import 'brace/theme/monokai' let editor = ace.edit(element) ...

Full-fledged example for an Unpoly compiler that will improve your <textarea html-editor>:

Copy
import ace from 'brace' import 'brace/mode/html' import 'brace/theme/monokai' up.compiler('[html-editor]', ($element) => { let $editorContainer = $('<div>').insertAfter($element) let editor = ace.edit($editorContainer.get(0)) let session = editor.getSession() editor.setOptions({ mode: 'ace/mode/html', theme: 'ace/theme/monokai', minLines: 50, maxLines: 50, fontSize: '16px', wrap: true, useSoftTabs: true, tabSize: 2, }) // If we enable Ace on the textarea directly, it will lose its value and never send any changes to the server. // Instead, we use a container element and sync any changes into the textarea. $element.hide() session.setValue($element.val()) session.on('change', () => { $element.val(session.getValue()) }) return () => { editor.destroy() } })

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
15 days ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more