Skip to content

Commit 50394ca

Browse files
tksktojp-knjyanthomasdev
authored
i18n(ja): update guides/imports.mdx (#12449)
Co-authored-by: knj <[email protected]> Co-authored-by: Yan <[email protected]>
1 parent 7306a26 commit 50394ca

File tree

1 file changed

+187
-25
lines changed

1 file changed

+187
-25
lines changed

src/content/docs/ja/guides/imports.mdx

Lines changed: 187 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,21 @@ Astroは、標準で以下のファイル形式をサポートしています。
2323
- CSS Modules(`.module.css`
2424
- イメージとアセット(`.svg``.jpg``.png`など)
2525

26-
さらに、Astroを拡張して、React、Svelte、Vueコンポーネントなど、さまざまな[UIフレームワーク](/ja/guides/framework-components/)のサポートを追加できます。また、[Astro MDXインテグレーション](/ja/guides/integrations-guide/mdx/)をインストールし、プロジェクトで`.mdx`ファイルを使用することもできます
26+
さらに、Astroを拡張して、React、Svelte、Vueコンポーネントなど、さまざまな[UIフレームワーク](/ja/guides/framework-components/)のサポートを追加できます。また、[Astro MDXインテグレーション](/ja/guides/integrations-guide/mdx/)[Astro Markdocインテグレーション](/ja/guides/integrations-guide/markdoc/)をインストールし、`.mdx`ファイルや`.mdoc`ファイルも使用できます
2727

2828
### `public/`内のファイル
2929

30-
プロジェクトの[`public/`ディレクトリ](/ja/basics/project-structure/#public)には、任意の静的アセットを置けます。Astroはそれをそのまま最終ビルドとして直接コピーします。HTMLテンプレートの中では、`public/`内のファイルをURLパスで直接参照できます。
30+
プロジェクトの[`public/`ディレクトリ](/ja/basics/project-structure/#public)には、任意の静的アセットを置けます。Astroはそれをそのまま最終ビルドとして直接コピーします。`public/`内のファイルはビルドやバンドルの対象とならないため、あらゆる種類のファイルがサポートされます。
31+
32+
HTMLテンプレートからは、URLパスで `public/` 内のファイルを直接参照できます。
33+
34+
```astro
35+
// /public/reports/annual/2024.pdf へのリンク
36+
<a href="/reports/annual/2024.pdf">2024年の年次報告書(PDF)をダウンロード</a>
37+
38+
// /public/assets/cats/ginger.jpg を表示
39+
<img src="/assets/cats/ginger.jpg" alt="ベッドで眠るオレンジ色の猫。">
40+
```
3141

3242

3343
## Import構文
@@ -135,12 +145,15 @@ CSSモジュールは、スタイルシートのために一意に生成され
135145
### その他のアセット
136146

137147
```jsx
138-
import imgReference from './image.png'; // img === '/src/image.png'
139-
import svgReference from './image.svg'; // svg === '/src/image.svg'
140-
import txtReference from './words.txt'; // txt === '/src/words.txt'
148+
// `src`などのプロパティを持つオブジェクトを取得します
149+
import imgReference from './image.png';
150+
import svgReference from './image.svg';
141151

142-
// この例ではJSXを使用していますが、どのようなフレームワークでもインポート参照を使用できます。
152+
// HTMLやUIフレームワークのコンポーネントでは明示的に`src`プロパティを指定します
143153
<img src={imgReference.src} alt="画像の説明" />;
154+
155+
// Astroの`<Image />`と`<Picture />`コンポーネントはデフォルトで`src`を参照します
156+
<Image src={imgReference} alt="画像の説明">
144157
```
145158

146159
上記で明示されていないその他のアセットは、ESMの `import` を使ってインポートすることができ、最終的にビルドされたアセットへのURLリファレンスを返します。これは、JS以外のアセットをURLで参照する場合に便利です。たとえば、画像要素を作成して、その画像を指す`src`属性を指定できます。
@@ -170,23 +183,18 @@ import logoUrl from '../../assets/logo.png?url';
170183

171184
インポートエイリアスは`tsconfig.json`から追加できます。
172185

173-
```json title="tsconfig.json" ins={5-6}
186+
```json title="tsconfig.json" ins={4-5}
174187
{
175188
"compilerOptions": {
176-
"baseUrl": ".",
177189
"paths": {
178-
"@components/*": ["src/components/*"],
179-
"@assets/*": ["src/assets/*"]
190+
"@components/*": ["./src/components/*"],
191+
"@assets/*": ["./src/assets/*"]
180192
}
181193
}
182194
}
183195
```
184196

185-
:::note
186-
エイリアスのパスが解決できるように`compilerOptions.baseUrl`が設定されていることを確認してください。
187-
:::
188-
189-
設定を変更すると、開発サーバーが自動的に再起動します。これにより、プロジェクト内の任意の場所でエイリアスを使用してインポートできるようになりました。
197+
設定を変更すると、開発サーバーが自動的に再起動します。これにより、プロジェクト内の任意の場所でエイリアスを使用してインポートできます。
190198

191199
```astro title="src/pages/about/company.astro" ins="@components" ins="@assets"
192200
---
@@ -195,7 +203,158 @@ import logoUrl from '@assets/logo.png?url';
195203
---
196204
```
197205

198-
これらのエイリアスは、[VS Code](https://code.visualstudio.com/docs/languages/jsconfig)や他のエディタにも自動的に統合されます。
206+
## `import.meta.glob()`
207+
208+
Viteの[`import.meta.glob()`](https://vite.dev/guide/features.html#glob-import)は、globパターンで多数のファイルを一度にインポートする方法です。
209+
210+
`import.meta.glob()`は、インポートしたいローカルファイルを示す[globパターン](#globパターン)を引数として受け取ります。戻り値は、マッチしたファイルのパスをキーとするオブジェクトです。モジュールを同期的に読み込むには、第2引数に`{ eager: true }`を渡します。
211+
212+
```astro title="src/components/my-component.astro" {3,4}
213+
---
214+
// `./src/pages/post/`内の`.md`で終わるすべてのファイルをインポート
215+
const matches = import.meta.glob('../pages/post/*.md', { eager: true });
216+
const posts = Object.values(matches);
217+
---
218+
<!-- ブログ投稿の最初の5つを<article>としてレンダリングする -->
219+
<div>
220+
{posts.slice(0, 4).map((post) => (
221+
<article>
222+
<h2>{post.frontmatter.title}</h2>
223+
<p>{post.frontmatter.description}</p>
224+
<a href={post.url}>もっと読む</a>
225+
</article>
226+
))}
227+
</div>
228+
```
229+
230+
`import.meta.glob`でインポートしたAstroコンポーネントは、[`AstroInstance`](#astroファイル)型です。各コンポーネントのインスタンスは、その`default`プロパティでレンダリングできます。
231+
232+
```astro title="src/pages/component-library.astro" {8}
233+
---
234+
// `./src/components/`内の`.astro`で終わるすべてのファイルをインポート
235+
const components = Object.values(import.meta.glob('../components/*.astro', { eager: true }));
236+
---
237+
<!-- すべてのコンポーネントを表示 -->
238+
{components.map((component) => (
239+
<div>
240+
<component.default size={24} />
241+
</div>
242+
))}
243+
```
244+
245+
### サポートされる値
246+
247+
Viteの`import.meta.glob()`は静的な文字列リテラルのみをサポートし、動的な変数や文字列補間は使えません。
248+
249+
回避策として、必要なファイルをすべて含む、より広いパターンを指定しておいて、あとから絞り込む方法があります。
250+
251+
```astro {6-7}
252+
---
253+
// src/components/featured.astro
254+
const { postSlug } = Astro.props;
255+
const pathToMyFeaturedPost = `src/pages/blog/${postSlug}.md`;
256+
257+
const posts = Object.values(import.meta.glob("../pages/blog/*.md", { eager: true }));
258+
const myFeaturedPost = posts.find(post => post.file.includes(pathToMyFeaturedPost));
259+
---
260+
261+
<p>
262+
お気に入りの投稿をみてください! <a href={myFeaturedPost.url}>{myFeaturedPost.frontmatter.title}</a>
263+
</p>
264+
```
265+
266+
### インポート時の型ユーティリティ
267+
268+
#### Markdownファイル
269+
270+
`import.meta.glob()`で読み込まれたMarkdownファイルは、`MarkdownInstance`インターフェースを持ちます。
271+
272+
```ts
273+
export interface MarkdownInstance<T extends Record<string, any>> {
274+
/* YAML/TOMLフロントマターで指定されたデータ */
275+
frontmatter: T;
276+
/* ファイルの絶対パス */
277+
file: string;
278+
/* ファイルのレンダリング後のパス */
279+
url: string | undefined;
280+
/* ファイルの内容をレンダリングするAstroコンポーネント */
281+
Content: AstroComponentFactory;
282+
/** (Markdownのみ)レイアウトHTMLとYAML/TOMLフロントマターを除く生のMarkdownコンテンツ */
283+
rawContent(): string;
284+
/** (Markdownのみ)レイアウトHTMLを除いたHTMLにコンパイル済みのMarkdown */
285+
compiledContent(): string;
286+
/* ファイル内の h1〜h6 要素の配列を返す関数 */
287+
getHeadings(): Promise<{ depth: number; slug: string; text: string }[]>;
288+
default: AstroComponentFactory;
289+
}
290+
```
291+
292+
TypeScriptのジェネリクスを使って、`frontmatter`変数に型を指定できます。
293+
294+
```astro
295+
---
296+
import type { MarkdownInstance } from 'astro';
297+
interface Frontmatter {
298+
title: string;
299+
description?: string;
300+
}
301+
302+
const posts = Object.values(import.meta.glob<MarkdownInstance<Frontmatter>>('./posts/**/*.md', { eager: true }));
303+
---
304+
305+
<ul>
306+
{posts.map(post => <li>{post.frontmatter.title}</li>)}
307+
</ul>
308+
```
309+
310+
#### Astroファイル
311+
312+
Astroファイルは次のインターフェースを持ちます。
313+
314+
```ts
315+
export interface AstroInstance {
316+
/* ファイルのパス */
317+
file: string;
318+
/* ファイルのURL(pagesディレクトリにある場合) */
319+
url: string | undefined;
320+
default: AstroComponentFactory;
321+
}
322+
```
323+
324+
#### その他のファイル
325+
326+
その他のファイルのインターフェースはさまざまですが、ファイルの中身が分かっている場合は、`import.meta.glob()` にTypeScriptのジェネリクスを指定できます。
327+
328+
```ts
329+
---
330+
interface CustomDataFile {
331+
default: Record<string, any>;
332+
}
333+
const data = import.meta.glob<CustomDataFile>('../data/**/*.js');
334+
---
335+
```
336+
337+
### globパターン
338+
339+
globパターンは、特殊なワイルドカード文字をサポートするファイルパスです。プロジェクト内の複数のファイルを一度に参照する場合に使用します。
340+
341+
たとえば、globパターン`./pages/**/*.{md,mdx}`は、pagesサブディレクトリで始まり、そのサブディレクトリをすべて調べ(`/**`)、 ファイル名(`/*`)が`.md`または`.mdx`で終わる(`.{md,mdx}`)ファイルにマッチします。
342+
343+
#### Astroにおけるglobパターン
344+
345+
`import.meta.glob()`を使用する場合、引数として指定するglobパターンは文字列リテラルである必要があり、変数を含むことはできません。
346+
347+
また、globパターンは、以下のいずれかで始まる必要があります。
348+
349+
- `./`(カレントディレクトリを基準にする)
350+
- `../`(親ディレクトリを基準にする)
351+
- `/`(プロジェクトのルートを基準にする)
352+
353+
globパターンの構文の詳細は[picomatchのリポジトリ](https://github.com/micromatch/picomatch#globbing-features)をご覧ください。
354+
355+
### `import.meta.glob()``getCollection()`
356+
357+
[コンテンツコレクション](/ja/guides/content-collections/)は、複数ファイルの読み込みに`import.meta.glob()`の代わりとなる[`getCollection()` API](/ja/reference/modules/astro-content/#getcollection)を提供します。Markdown/MDX/Markdocなどのコンテンツファイルが`src/content/`配下のコレクションにある場合は、`getCollection()`を使って[コレクションをクエリ](/ja/guides/content-collections/#コレクションのクエリ)し、コンテンツを取得します。
199358

200359
## WASM
201360

@@ -209,26 +368,29 @@ Astroは、ブラウザの[`WebAssembly`](https://developer.mozilla.org/ja/docs/
209368

210369
## Nodeビルトイン
211370

212-
Astroのユーザーには、可能な限りNode.jsのビルトイン(`fs``path`など)を避けることをおすすめします。Astroは、[アダプター](/ja/guides/on-demand-rendering/)を使用して複数のランタイムと互換性があります。これには、`fs`などのNodeビルトインモジュールをサポートしない[Deno](https://github.com/denoland/deno-astro-adapter)[Cloudflare Workers](/ja/guides/integrations-guide/cloudflare/)が含まれます
371+
AstroはNode.jsのビルトインを、いくつかの制限付きで`node:`プレフィックス経由でサポートします。開発と本番で挙動が異なる場合や、オンデマンドレンダリングと互換性がない機能もあります。いくつかの[アダプター](/ja/guides/on-demand-rendering/)は、これらのビルトインと互換性がない、または一部のみサポートするための設定が必要な場合があります(例: [Cloudflare Workers](/ja/guides/integrations-guide/cloudflare/)[Deno](https://github.com/denoland/deno-astro-adapter)
213372

214-
私たちの目的は、一般的なNode.jsのビルトインに対するAstroの代替機能を提供することです。しかし、今のところそのような代替機能は存在しません。ですから、もし本当にこれらのビルトインモジュールを使う必要があるのなら、それを止めたいとは思いません。AstroはNode.jsのビルトインを、Nodeの新しいプレフィックスである`node:`を使ってサポートしています。たとえば、ファイルを読み込む場合、次のようにします
373+
次の例では、Nodeの`util`モジュールを読み込み、MIMEタイプを解析しています
215374

216375
```astro title="src/components/MyComponent.astro"
217376
---
218-
// 例: Node.js から "fs/promises" ビルトインをインポートします。
219-
import fs from 'node:fs/promises';
377+
// 例: Node.jsの "util" ビルトインをインポート
378+
import util from 'node:util';
379+
380+
export interface Props {
381+
mimeType: string,
382+
}
220383
221-
const url = new URL('../../package.json', import.meta.url);
222-
const json = await fs.readFile(url, 'utf-8');
223-
const data = JSON.parse(json);
384+
const mime = new util.MIMEType(Astro.props.mimeType)
224385
---
225386
226-
<span>Version: {data.version}</span>
387+
<span>Type: {mime.type}</span>
388+
<span>SubType: {mime.subtype}</span>
227389
```
228390

229391
## ファイル形式のサポートを拡張
230392

231-
**Vite**と互換性のある**Rollup**プラグインを使用すると、Astroがネイティブでサポートしていないファイル形式をインポートできます。必要なプラグインがどこにあるかは、Viteドキュメントの[プラグインの検索](https://ja.vite.dev/guide/using-plugins.html#プラグインの検索)セクションを参照してください。
393+
**Vite**と互換性のある**Rollup**プラグインを使用すると、Astroがネイティブでサポートしていないファイル形式をインポートできます。必要なプラグインがどこにあるかは、Viteドキュメントの[プラグインの検索](https://ja.vite.dev/guide/using-plugins.html#プラグインの検索)セクションを参照してください。
232394

233395
:::note[プラグイン設定]
234396
設定オプションや正しいインストール方法については、プラグインのドキュメントを参照してください。

0 commit comments

Comments
 (0)