DEV Community

loading...

code-block v0.1 web component released

justinribeiro profile image Justin Ribeiro Originally published at justinribeiro.com on ・2 min read

Over the last couple of months I’ve gotten a few emails asking how exactly I make my code samples on this blog work. In the past that would have been a harder question to answer (my original web component for this was less than ideal) but with my recent spring updates, I thought it would be nice to break out that very feature.

Announcing <code-block>, a LitElement-based web component that utilizes Prism.js.

pre in action

It’s available on npm:

$ npm i @justinribeiro/pre $ yarn add @justinribeiro/pre

Or you can grab it from the repo:

$ git clone git@github.com:justinribeiro/pre.git

From there, just write code in the element like any ‘ol html element.

\<pre language="fortran" theme="/node\_modules/prismjs/themes/prism-okaidia.css"\> program HelloWorld write (\*,\*) 'Hello, world!' ! This is an inline comment end program HelloWorld \</pre\>

Like the version I run on this blog, this component uses dynamic language imports that way you don’t have to carry additional weight in your bundle (load only what you need). The v0.1.0 version also includes support for themes, so you can just pass it the path of a theme CSS file and it’ll do the rest.

The biggest hurdle with this setup is that you have to make sure you take the /node_modules/prismjs/**, otherwise the loading doesn’t quite work correctly. I considered alternative approaches, but mostly it had me duplicating large portions of Prism’s language support and that seemed very ill-advised.

In the future I’d like to see if I can enable Prism’s vast plugin support. In the mean time, grab it, embed some code somewhere, web component style.

Discussion (0)

pic
Editor guide