首頁 > web前端 > css教學 > 代碼塊,但更好

代碼塊,但更好

Joseph Gordon-Levitt
發布: 2025-03-23 10:03:13
原創
694 人瀏覽過

Code blocks, but better

Pedro Duarte made a wishlist for styled code blocks in blog posts and documentation, then hand-rolls a perfect solution for that wishlist. For example, a feature to be able to highlight certain lines or words within the code block. The line highlighter is unique in that it only syntax highlights the highlighted lines, leaving the rest gray, which is a neat way to draw focus. And the word highlighter works via a RegEx. Pedro notes this isn’t a tutorial, it’s just a showcase of all the features that were stitched together using an existing combination of custom code and existing libraries. It’s pretty specific to React + Next.js + MDX, but apparently the core of it is based on rehype, which is new to me.

The results are pretty darn nice, modern-looking code blocks if you ask me! At the same time, I think it’s equally notable what’s not there as opposed to what is. I’ve seen (and tried) really featured-packed code blocks in the past, with features like a copy to clipboard button, a view raw code button, and export to whatever services. Pedro’s code blocks don’t even have an option to show the language in use.

Everybody’s wishlist is different. One thing that isn’t on Pedro’s wishlist is server-side rendering, but you can see on the blog post itself that it totally works with that (it’s presumably just Next.js at work). I’m pretty envious of that. Even though we’re ultimately both using Prism.js as the syntax highlighter, I’m only using it client-side. It occurs to me now that I could perhaps pull all this off in a Cloudflare Worker by using the HTMLRewriter — meaning it would essentially look like it’s done server-side and I could rip off the client-side copy of Prism. Maybe even more ideally, though, is that I’d do it as a WordPress plugin. Basically a PHP port of Prism, which seems like a tall order.

My wishlist for code block plugin…

  • Syntax highlighting (both on the rendered site and while authoring)
  • Server-side rendered stuff for syntax highlighting
  • Works nicely with the native WordPress block editor code blocks (```). For example, pasting in a code block auto-detects and uses the correct block. Easy to convert code to and from this kind of block.
  • Optional line highlighter
  • Optional line numbers
  • Optional word highlighter
  • Optional language display (and the ability to override that label)
  • Copy and paste very cleanly
  • No need to escape code while authoring
  • Freedom to style however on the front end (for modes, themes, custom scrollbars, etc). Styling code blocks has a million things to consider, so smart defaults should probably come with the plugin, but easy to override.
  • Stretch goal: can it somehow help with inline code as well?

以上是代碼塊,但更好的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板