DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Peter Solopov
Peter Solopov

Posted on

~40 lines code editor in pure js

There are many awesome full-features code editors like CodeMirror, Ace, and Monaco. But if you want to edit small code snippets you probably want to use tiny editor and keep your bundle size small. Also, you can create your own!

Plan

  1. Create a class Editor. The constructor take CSS selector and options: initial value and highlighter function.
  2. Create pre and textarea elements.
  3. Listen to textarea input event.
  4. Add HTML to pre element with external highlighter when textarea is changed.

Trick

We will be interacting with textarea element but see only highlighted HTML in pre element. textarea text will be hidden by CSS rule -webkit-text-fill-color: transparent.

Alt Text

Uses

You can check all code in sandbox

import Editor from './Editor.js'
// use highligh.js as external highlighter
import hljs form "highlight.js"

const editor = new Editor('#editor', {
  value: "my awesome code",
  highlighter: value => hljs.highlight("javascript", value).value
})

editor.onUpdate(value => console.log(value));

Live demo

Conclusion

If you don't need features like code folding, multi cursors, etc., you can create your code editor to keep your bundle size small.

If you need tiny editor with only features you want, like line numbers, handling tab for indentation, cut line, etc. you can check yace:

GitHub logo petersolopov / yace

yet another code editor for browser

It's lightweight ~1KB code editor, with ability to add your plugins. It also uses textarea + pre idea.

Thanks

Top comments (0)

We are hiring! Do you want to be our Senior Platform Engineer? Are you capable of chipping in across sysadmin, ops, and site reliability work, while supporting the open source stack that runs DEV and other communities?

This role might just be for you!

Apply now