首页 > 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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板