Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
212 changes: 187 additions & 25 deletions src/content/docs/ja/guides/imports.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,21 @@ Astroは、標準で以下のファイル形式をサポートしています。
- CSS Modules(`.module.css`)
- イメージとアセット(`.svg`、`.jpg`、`.png`など)

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

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

プロジェクトの[`public/`ディレクトリ](/ja/basics/project-structure/#public)には、任意の静的アセットを置けます。Astroはそれをそのまま最終ビルドとして直接コピーします。HTMLテンプレートの中では、`public/`内のファイルをURLパスで直接参照できます。
プロジェクトの[`public/`ディレクトリ](/ja/basics/project-structure/#public)には、任意の静的アセットを置けます。Astroはそれをそのまま最終ビルドとして直接コピーします。`public/`内のファイルはビルドやバンドルの対象とならないため、あらゆる種類のファイルがサポートされます。

HTMLテンプレートからは、URLパスで `public/` 内のファイルを直接参照できます。

```astro
// /public/reports/annual/2024.pdf へのリンク
<a href="/reports/annual/2024.pdf">2024年の年次報告書(PDF)をダウンロード</a>

// /public/assets/cats/ginger.jpg を表示
<img src="/assets/cats/ginger.jpg" alt="ベッドで眠るオレンジ色の猫。">
```


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

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

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

// Astroの`<Image />`と`<Picture />`コンポーネントはデフォルトで`src`を参照します
<Image src={imgReference} alt="画像の説明">
```

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

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

```json title="tsconfig.json" ins={5-6}
```json title="tsconfig.json" ins={4-5}
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@components/*": ["src/components/*"],
"@assets/*": ["src/assets/*"]
"@components/*": ["./src/components/*"],
"@assets/*": ["./src/assets/*"]
}
}
}
```

:::note
エイリアスのパスが解決できるように`compilerOptions.baseUrl`が設定されていることを確認してください。
:::

設定を変更すると、開発サーバーが自動的に再起動します。これにより、プロジェクト内の任意の場所でエイリアスを使用してインポートできるようになりました。
設定を変更すると、開発サーバーが自動的に再起動します。これにより、プロジェクト内の任意の場所でエイリアスを使用してインポートできます。

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

これらのエイリアスは、[VS Code](https://code.visualstudio.com/docs/languages/jsconfig)や他のエディタにも自動的に統合されます。
## `import.meta.glob()`

Viteの[`import.meta.glob()`](https://vite.dev/guide/features.html#glob-import)は、globパターンで多数のファイルを一度にインポートする方法です。

`import.meta.glob()`は、インポートしたいローカルファイルを示す[globパターン](#globパターン)を引数として受け取ります。戻り値は、マッチしたファイルのパスをキーとするオブジェクトです。モジュールを同期的に読み込むには、第2引数に`{ eager: true }`を渡します。

```astro title="src/components/my-component.astro" {3,4}
---
// `./src/pages/post/`内の`.md`で終わるすべてのファイルをインポート
const matches = import.meta.glob('../pages/post/*.md', { eager: true });
const posts = Object.values(matches);
---
<!-- ブログ投稿の最初の5つを<article>としてレンダリングする -->
<div>
{posts.slice(0, 4).map((post) => (
<article>
<h2>{post.frontmatter.title}</h2>
<p>{post.frontmatter.description}</p>
<a href={post.url}>もっと読む</a>
</article>
))}
</div>
```

`import.meta.glob`でインポートしたAstroコンポーネントは、[`AstroInstance`](#astroファイル)型です。各コンポーネントのインスタンスは、その`default`プロパティでレンダリングできます。

```astro title="src/pages/component-library.astro" {8}
---
// `./src/components/`内の`.astro`で終わるすべてのファイルをインポート
const components = Object.values(import.meta.glob('../components/*.astro', { eager: true }));
---
<!-- すべてのコンポーネントを表示 -->
{components.map((component) => (
<div>
<component.default size={24} />
</div>
))}
```

### サポートされる値

Viteの`import.meta.glob()`は静的な文字列リテラルのみをサポートし、動的な変数や文字列補間は使えません。

回避策として、必要なファイルをすべて含む、より広いパターンを指定しておいて、あとから絞り込む方法があります。

```astro {6-7}
---
// src/components/featured.astro
const { postSlug } = Astro.props;
const pathToMyFeaturedPost = `src/pages/blog/${postSlug}.md`;

const posts = Object.values(import.meta.glob("../pages/blog/*.md", { eager: true }));
const myFeaturedPost = posts.find(post => post.file.includes(pathToMyFeaturedPost));
---

<p>
お気に入りの投稿をみてください! <a href={myFeaturedPost.url}>{myFeaturedPost.frontmatter.title}</a>
</p>
```

### インポート時の型ユーティリティ

#### Markdownファイル

`import.meta.glob()`で読み込まれたMarkdownファイルは、`MarkdownInstance`インターフェースを持ちます。

```ts
export interface MarkdownInstance<T extends Record<string, any>> {
/* YAML/TOMLフロントマターで指定されたデータ */
frontmatter: T;
/* ファイルの絶対パス */
file: string;
/* ファイルのレンダリング後のパス */
url: string | undefined;
/* ファイルの内容をレンダリングするAstroコンポーネント */
Content: AstroComponentFactory;
/** (Markdownのみ)レイアウトHTMLとYAML/TOMLフロントマターを除く生のMarkdownコンテンツ */
rawContent(): string;
/** (Markdownのみ)レイアウトHTMLを除いたHTMLにコンパイル済みのMarkdown */
compiledContent(): string;
/* ファイル内の h1〜h6 要素の配列を返す関数 */
getHeadings(): Promise<{ depth: number; slug: string; text: string }[]>;
default: AstroComponentFactory;
}
```

TypeScriptのジェネリクスを使って、`frontmatter`変数に型を指定できます。

```astro
---
import type { MarkdownInstance } from 'astro';
interface Frontmatter {
title: string;
description?: string;
}

const posts = Object.values(import.meta.glob<MarkdownInstance<Frontmatter>>('./posts/**/*.md', { eager: true }));
---

<ul>
{posts.map(post => <li>{post.frontmatter.title}</li>)}
</ul>
```

#### Astroファイル

Astroファイルは次のインターフェースを持ちます。

```ts
export interface AstroInstance {
/* ファイルのパス */
file: string;
/* ファイルのURL(pagesディレクトリにある場合) */
url: string | undefined;
default: AstroComponentFactory;
}
```

#### その他のファイル

その他のファイルのインターフェースはさまざまですが、ファイルの中身が分かっている場合は、`import.meta.glob()` にTypeScriptのジェネリクスを指定できます。

```ts
---
interface CustomDataFile {
default: Record<string, any>;
}
const data = import.meta.glob<CustomDataFile>('../data/**/*.js');
---
```

### globパターン

globパターンは、特殊なワイルドカード文字をサポートするファイルパスです。プロジェクト内の複数のファイルを一度に参照する場合に使用します。

たとえば、globパターン`./pages/**/*.{md,mdx}`は、pagesサブディレクトリで始まり、そのサブディレクトリをすべて調べ(`/**`)、 ファイル名(`/*`)が`.md`または`.mdx`で終わる(`.{md,mdx}`)ファイルにマッチします。

#### Astroにおけるglobパターン

`import.meta.glob()`を使用する場合、引数として指定するglobパターンは文字列リテラルである必要があり、変数を含むことはできません。

また、globパターンは、以下のいずれかで始まる必要があります。

- `./`(カレントディレクトリを基準にする)
- `../`(親ディレクトリを基準にする)
- `/`(プロジェクトのルートを基準にする)

globパターンの構文の詳細は[picomatchのリポジトリ](https://github.com/micromatch/picomatch#globbing-features)をご覧ください。

### `import.meta.glob()`と`getCollection()`

[コンテンツコレクション](/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/#コレクションのクエリ)し、コンテンツを取得します。

## WASM

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

## Nodeビルトイン

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/)が含まれます
AstroはNode.jsのビルトインを、いくつかの制限付きで`node:`プレフィックス経由でサポートします。開発と本番で挙動が異なる場合や、オンデマンドレンダリングと互換性がない機能もあります。いくつかの[アダプター](/ja/guides/on-demand-rendering/)は、これらのビルトインと互換性がない、または一部のみサポートするための設定が必要な場合があります(例: [Cloudflare Workers](/ja/guides/integrations-guide/cloudflare/)、[Deno](https://github.com/denoland/deno-astro-adapter)

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

```astro title="src/components/MyComponent.astro"
---
// 例: Node.js から "fs/promises" ビルトインをインポートします。
import fs from 'node:fs/promises';
// 例: Node.jsの "util" ビルトインをインポート
import util from 'node:util';

export interface Props {
mimeType: string,
}

const url = new URL('../../package.json', import.meta.url);
const json = await fs.readFile(url, 'utf-8');
const data = JSON.parse(json);
const mime = new util.MIMEType(Astro.props.mimeType)
---

<span>Version: {data.version}</span>
<span>Type: {mime.type}</span>
<span>SubType: {mime.subtype}</span>
```

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

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

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