👀
コンポーネントのデモとコードを表示したい
やりたいこと
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