docs icon indicating copy to clipboard operation
docs copied to clipboard

Suggestion to improve the docs for the Code component

Open ttmc opened this issue 1 year ago • 4 comments

The docs about the Code component give examples of how you could use it in an Astro file (.astro):

---
import { Code } from 'astro:components';
---
<!-- Syntax highlight some JavaScript code. -->
<Code code={`const foo = 'bar';`} lang="js" />
<!-- Optional: Customize your theme. -->
<Code code={`const foo = 'bar';`} lang="js" theme="dark-plus" />
<!-- Optional: Enable word wrapping. -->
<Code code={`const foo = 'bar';`} lang="js" wrap />
<!-- Optional: Output inline code. -->
<p>
  <Code code={`const foo = 'bar';`} lang="js" inline />
  will be rendered inline.
</p>

I found that one must be very careful to inspect their code and replace \n with \\n, otherwise it will be converted to an actual newline in the rendered output. Similarly, \t must be replaced with \\t, and so on. Backticks-in-code must also be escaped. Doing that is tricky and error-prone. Ideally, one could just copy some raw code from their IDE/text editor straight into their .astro file, somewhere, and be done.

Good news: it's possible, and here's how... just append String.raw before the first backtick. That way everything inside the backticks will be interepreted as a raw string.

The above example code, in the docs, would become:

---
import { Code } from 'astro:components';
---
<!-- Syntax highlight some JavaScript code. -->
<Code code={String.raw`const foo = 'bar';`} lang="js" />
<!-- Optional: Customize your theme. -->
<Code code={String.raw`const foo = 'bar';`} lang="js" theme="dark-plus" />
<!-- Optional: Enable word wrapping. -->
<Code code={String.raw`const foo = 'bar';`} lang="js" wrap />
<!-- Optional: Output inline code. -->
<p>
  <Code code={String.raw`const foo = 'bar';`} lang="js" inline />
  will be rendered inline.
</p>

ttmc avatar Feb 28 '24 15:02 ttmc

The same change could be made to the example code given in the Astro docs about the Prism component, i.e.

---
import { Prism } from '@astrojs/prism';
---
<Prism lang="js" code={String.raw`const foo = 'bar';`} />

ttmc avatar Feb 28 '24 16:02 ttmc