👀

コンポーネントのデモとコードを表示したい

2025/02/02に公開

やりたいこと

UIコンポーネントのデモページを開いてみると、デモとそのコードが表示されていることが多い。
あれをやってみたい。
例1
React - Learn
例2
MuiのButton

結論

Viteのimport.meta.globを使う。

import.meta.globって?

Viteが提供する、特定のディレクトリ内のファイルをまとめて取得する機能。
次の例では、compenentsフォルダ以下すべての.tsxまたは.tsファイルをオブジェクトとして取得する。

const files = import.meta.glob("../components/**/*.{tsx,ts}");
console.log(files);

結果こんな感じ。

さらに、queryオプション`を利用してファイルのソースコードを文字列として取する。

- const files = import.meta.glob("../components/**/*.{tsx,ts}");

const files = import.meta.glob(
 "../components/**/*.{tsx,ts}",
+ {
+ query: "?raw",
+ import: "default",
+ }
);

console.log(codeFiles["./mui/MuiButton.tsx"]);

consoleの結果

文字列として取得しているので、<div>タグなどで囲むことによってHTMLに表示可能。
赤色の枠で囲われているコードが、import.meta.globで取得したコードを表示している。

せっかくなのでシンタックスハイライトを適用

使用するライブラリはReact Syntax Highlighter
インストール。

npm install react-syntax-highlighter --save
npm install @types/react-syntax-highlighter --save-dev

使い方はSyntaxHighlighterにシンタックスハイライトを使用する言語、表示するスタイルをそれぞれ指定すればOK。シンプルですね。

import SyntaxHighlighter from "react-syntax-highlighter";
import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism";

const CodeViewer = () => {
  const code = "const testString = 'テストだよ!` console.log(testString)";
  return (
    <div>
      <SyntaxHighlighter language="tsx" style={dracula}>
        {code}
      </SyntaxHighlighter>
    </div>
  );
};

export default CodeViewer;

結果

いい感じ。個人的には行番号が欲しいのでshowLineNumbersを追加。

import SyntaxHighlighter from "react-syntax-highlighter";
import { dracula } from "react-syntax-highlighter/dist/esm/styles/prism";

const CodeViewer = () => {
  const code = "const testString = 'テストだよ!` console.log(testString)";
  return (
    <div>
-      <SyntaxHighlighter language="tsx" style={dracula}>
+      <SyntaxHighlighter language="tsx" style={dracula} showLineNumbers>
        {code}
      </SyntaxHighlighter>
    </div>
  );
};

export default CodeViewer;

結果。行番号が表示されましたね。

あとはimport.meta.globから取得したコードをpropsとして渡してあげれば完成。

import SyntaxHighlighter from "react-syntax-highlighter";
import { dracula } from "react-syntax-highlighter/dist/esm/styles/prism";

+ export type CodeViewerPorps = {
+  code: string;
+ };

- const CodeViewer = () => {
+ const CodeViewer = ({ code }: CodeViewerPorps) => {
  return (
    <div>
      <SyntaxHighlighter language="tsx" style={dracula} showLineNumbers>
        {code}
      </SyntaxHighlighter>
    </div>
  );
};

export default CodeViewer;

結果。これで完成。

最後に

デモとコードを表示するためには、いちいちコピペしないといけないのかな~と思って調べていたら便利な物がすでに用意されていた。
今回のようにどんどん使ってみたいですね。

Discussion