t

Trevor Blades

AboutProjectsLabOSS
Subscribe

Code Block Alchemy

Building multi-language code samples

Code samples are a key component of any documentation site. They provide concise examples of how to use a particular software, and readers can often copy and paste code from docs and use them directly in their projects.

At Apollo, we build tools to help developers use GraphQL in their apps. One of our tools, Apollo Client, is a GraphQL client for JavaScript. But with TypeScript becoming so ubiquitous among developers of JavaScript apps, we needed a way to present code samples in TypeScript for those developers. We also wanted to keep our existing JavaScript examples for developers who aren't using TypeScript.

To do this, I built a remark plugin that transforms JavaScript code blocks into TypeScript code blocks and inserts them back into the page. Using an MDX component, I wrapped these adjacent code blocks and rendered a dropdown to control the visibility of the code block for the selected language.

I gave a talk on this subject at Reactadelphia in April 2020. Check it out below to learn more about the process of building these components.


npm i remark-typescript
Made with 🥥 in Burnaby, BC
© 2022 - Source code