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
- Create a class
Editor
. The constructor take CSS selector and options: initial value and highlighter function. - Create
pre
andtextarea
elements. - Listen to
textarea
input
event. - Add HTML to
pre
element with external highlighter whentextarea
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.
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
:
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.
Top comments (0)