Lightweight, extensible code editor component for the web using Prism
npm install prism-code-editor
Lightweight, extensible code editor component for the web using Prism.
. Libraries like CodeFlask, react-simple-code-editor, and many others have been doing this for years, but this library offers some distinct advantages:
javascript
import { minimalEditor, basicEditor, readonlyEditor } from "prism-code-editor/setups"
// Importing Prism grammars
import "prism-code-editor/prism/languages/markup"
const editor = basicEditor(
"#editor",
{
language: "html",
theme: "github-dark",
},
() => console.log("ready"),
)
`
Note: You might want to add display: grid to the container the editor is added to.
Advanced usage
For more advanced usage where you have full control over styling and the added extensions, check the documentation.
Usage with frameworks
This library has rewrites for both React and SolidJS. These rewrites better integrate with their respective framework than any wrapper ever could and are recommended if you're already using React or SolidJS.
- React rewrite
- SolidJS rewrite
Examples
- height: auto without layout shifts
- Simple tooltip example
- Autocomplete example
- Formatting with Prettier
- Relative line numbers
- Usage in forms
- Adding elements to code lines
- Custom cursor
Performance
All the code is tokenized each time for simplicity's sake. Even though only lines that change are updated in the DOM, the editor slows down as more code is added, although not as quickly as with zero optimizations.
Once you start exceeding 1000 LOC, the editor will start slowing down on most hardware. If you need to display that much code, consider a more robust/heavy library.
Compatibility
This has been tested to work in the latest desktop and mobile versions of both Safari, Chrome, and Firefox. It should work in slightly older browsers too, but there will be many bugs present in browsers that don't support beforeinput events.
This library does not support any Prism plugins since Prism hooks have been removed, but behavior like the Highlight Keywords plugin is included.
Some grammars have had small changes, most notably markup tags' grammar. Prism themes will work to style the tokens, but there can be some slight differences.
In PrismJS, greedy matching is controlled by a greedy flag on the token. Here, it's instead controlled by the g flag on the pattern. When copying Prism grammars, be sure to remove the greedy flags and instead add the g flag to the regex.
Lists of aliases are not supported. To add multiple aliases to a token, separate them with spaces in a single string instead. For example convert ["foo", "bar"] to "foo bar"`.