Skip to content

导入参考

Astro 支持大多数静态资源,且需要零配置。你可以在项目 JavaScript 中的任何位置使用 import 语句(包括 Astro frontmatter),Astro 将在你的最终构建中包含该静态资源的构建、优化副本。CSS 和 <style> 标签内部也支持 @import

¥Astro supports most static assets with zero configuration required. You can use the import statement anywhere in your project JavaScript (including your Astro frontmatter) and Astro will include a built, optimized copy of that static asset in your final build. @import is also supported inside of CSS & <style> tags.

¥Supported File Types

Astro 开箱即用地支持以下文件类型:

¥The following file types are supported out-of-the-box by Astro:

  • Astro 组件 (.astro)

  • Markdown(.md.markdown 等)

  • JavaScript(.js.mjs

  • TypeScript (.ts)

  • NPM 包

  • JSON (.json)

  • CSS (.css)

  • CSS 模块 (.module.css)

  • 图片和资源(.svg.jpg.png 等)

此外,你可以扩展 Astro 以添加对不同 用户界面框架 的支持,例如 React、Svelte 和 Vue 组件。你还可以安装 Astro MDX 集成Astro Markdoc 集成 以在你的项目中使用 .mdx.mdoc 文件。

¥Additionally, you can extend Astro to add support for different UI Frameworks like React, Svelte and Vue components. You can also install the Astro MDX integration or the Astro Markdoc integration to use .mdx or .mdoc files in your project.

¥Files in public/

你可以将任何静态资源放置在项目的 public/ 目录 中,Astro 会将其直接复制到你的最终版本中而不受影响。public/ 文件不是由 Astro 构建或打包的,这意味着支持任何类型的文件。

¥You can place any static asset in the public/ directory of your project, and Astro will copy it directly into your final build untouched. public/ files are not built or bundled by Astro, which means that any type of file is supported.

你可以直接在 HTML 模板中通过 URL 路径引用 public/ 文件。

¥You can reference a public/ file by a URL path directly in your HTML templates.

// To link to /public/reports/annual/2024.pdf
Download the <a href="/reports/annual/2024.pdf">2024 annual statement as a PDF</a>.
// To display /public/assets/cats/ginger.jpg
<img src="/assets/cats/ginger.jpg" alt="An orange cat sleeping on a bed.">

¥Import statements

Astro 使用 ESM,浏览器支持相同的 importexport 语法。

¥Astro uses ESM, the same import and export syntax supported in the browser.

import { getUser } from './user.js';

可以使用正常的 ESM importexport 语法导入 JavaScript。

¥JavaScript can be imported using normal ESM import & export syntax.

import { getUser } from './user';
import type { UserType } from './user';

Astro 包含对 TypeScript. You can import .ts and .tsx files directly in your Astro project, and even write TypeScript code directly inside your Astro component script 和任何 脚本标签 的内置支持。

¥Astro includes built-in support for TypeScript. You can import .ts and .tsx files directly in your Astro project, and even write TypeScript code directly inside your Astro component script and any script tags.

Astro 本身不执行任何类型检查。类型检查应该在 Astro 之外进行,可以通过 IDE 进行,也可以通过单独的脚本进行。对于 Astro 文件的类型检查,提供了 astro check 命令

¥Astro doesn’t perform any type checking itself. Type checking should be taken care of outside of Astro, either by your IDE or through a separate script. For type checking Astro files, the astro check command is provided.

Read more about TypeScript support in Astro.

¥NPM Packages

如果你已经安装了 NPM 包,则可以将其导入 Astro。

¥If you’ve installed an NPM package, you can import it in Astro.

---
import { Icon } from 'astro-icon';
---

如果使用旧格式发布包,Astro 将尝试将包转换为 ESM,以便 import 语句起作用。在某些情况下,你可能需要调整 vite 配置 才能正常工作。

¥If a package was published using a legacy format, Astro will try to convert the package to ESM so that import statements work. In some cases, you may need to adjust your vite config for it to work.

// Load the JSON object via the default export
import json from './data.json';

Astro 支持将 JSON 文件直接导入到你的应用中。导入的文件在默认导入中返回完整的 JSON 对象。

¥Astro supports importing JSON files directly into your application. Imported files return the full JSON object in the default import.

// Load and inject 'style.css' onto the page
import './style.css';

Astro 支持将 CSS 文件直接导入到你的应用中。导入的样式不会公开导出,但导入样式会自动将这些样式添加到页面中。默认情况下,这适用于所有 CSS 文件,并且可以通过插件支持编译为 CSS 语言,例如 Sass 和 Less。

¥Astro supports importing CSS files directly into your application. Imported styles expose no exports, but importing one will automatically add those styles to the page. This works for all CSS files by default, and can support compile-to-CSS languages like Sass & Less via plugins.

Read more about advanced CSS import use cases such as a direct URL reference for a CSS file, or importing CSS as a string in the Styling guide.

¥CSS Modules

// 1. Converts './style.module.css' classnames to unique, scoped values.
// 2. Returns an object mapping the original classnames to their final, scoped value.
import styles from './style.module.css';
// This example uses JSX, but you can use CSS Modules with any framework.
return <div className={styles.error}>Your Error Message</div>;

Astro 支持使用 [name].module.css 命名约定的 CSS 模块。与任何 CSS 文件一样,导入 CSS 文件会自动将该 CSS 应用到页面。但是,CSS 模块导出一个特殊的默认 styles 对象,该对象将原始类名映射到唯一标识符。

¥Astro supports CSS Modules using the [name].module.css naming convention. Like any CSS file, importing one will automatically apply that CSS to the page. However, CSS Modules export a special default styles object that maps your original classnames to unique identifiers.

CSS 模块可帮助你使用为样式表生成的唯一类名在前端强制执行组件作用域和隔离。

¥CSS Modules help you enforce component scoping & isolation on the frontend with uniquely-generated class names for your stylesheets.

¥Other Assets

import imgReference from './image.png'; // imgReference === '/src/image.png'
import svgReference from './image.svg'; // svgReference === '/src/image.svg'
import txtReference from './words.txt'; // txtReference === '/src/words.txt'
// This example uses JSX, but you can use import references with any framework.
<img src={imgReference.src} alt="image description" />;

上面未明确提及的所有其他资源都可以通过 ESM import 导入,并将返回对最终构建资源的 URL 引用。这对于通过 URL 引用非 JS 资源非常有用,例如创建具有指向该图片的 src 属性的图片元素。

¥All other assets not explicitly mentioned above can be imported via ESM import and will return a URL reference to the final built asset. This can be useful for referencing non-JS assets by URL, like creating an image element with a src attribute pointing to that image.

将图片放置在 public/ 文件夹中也很有用,如 项目结构页面 中所述。

¥It can also be useful to place images in the public/ folder as explained on the project-structure page.

Read more about appending Vite import parameters (e.g. ?url, ?raw) in Vite’s static asset handling guide.

¥Aliases

别名是一种为​​导入创建快捷方式的方法。

¥An alias is a way to create shortcuts for your imports.

别名可以帮助改善具有许多目录或相对导入的代码库的开发体验。

¥Aliases can help improve the development experience in codebases with many directories or relative imports.

src/pages/about/company.astro
---
import Button from '../../components/controls/Button.astro';
import logoUrl from '../../assets/logo.png?url';
---

在此示例中,开发者需要了解 src/pages/about/company.astrosrc/components/controls/Button.astrosrc/assets/logo.png 之间的树关系。然后,如果要移动 company.astro 文件,这些导入也需要更新。

¥In this example, a developer would need to understand the tree relationship between src/pages/about/company.astro, src/components/controls/Button.astro, and src/assets/logo.png. And then, if the company.astro file were to be moved, these imports would also need to be updated.

你可以在 tsconfig.json 中添加导入别名。

¥You can add import aliases in tsconfig.json.

tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@components/*": ["src/components/*"],
"@assets/*": ["src/assets/*"]
}
}
}

更改此配置后,开发服务器将自动重新启动。你现在可以在项目的任何位置使用别名进行导入:

¥The development server will automatically restart after this configuration change. You can now import using the aliases anywhere in your project:

src/pages/about/company.astro
---
import Button from '@components/controls/Button.astro';
import logoUrl from '@assets/logo.png?url';
---

这些别名也会自动集成到 VS Code 和其他编辑器中。

¥These aliases are also integrated automatically into VS Code and other editors.

Vite’s import.meta.glob() 是一种使用 glob 模式一次导入多个文件以查找匹配的文件路径的方法。

¥Vite’s import.meta.glob() is a way to import many files at once using glob patterns to find matching file paths.

import.meta.glob() 采用与你想要导入的本地文件匹配的相对 通配符模式 作为参数。它返回每个匹配文件导出的数组。要预先加载所有匹配的模块,请将 { eager: true } 作为第二个参数传递:

¥import.meta.glob() takes a relative glob pattern matching the local files you’d like to import as a parameter. It returns an array of each matching file’s exports. To load all matched modules up front, pass { eager: true } as the second argument:

src/components/my-component.astro
---
// imports all files that end with `.md` in `./src/pages/post/`
const matches = import.meta.glob('../pages/post/*.md', { eager: true });
const posts = Object.values(matches);
---
<!-- Renders an <article> for the first 5 blog posts -->
<div>
{posts.slice(0, 4).map((post) => (
<article>
<h2>{post.frontmatter.title}</h2>
<p>{post.frontmatter.description}</p>
<a href={post.url}>Read more</a>
</article>
))}
</div>

使用 import.meta.glob 导入的 Astro 组件属于 AstroInstance 类型。你可以使用每个组件实例的 default 属性来渲染它:

¥Astro components imported using import.meta.glob are of type AstroInstance. You can render each component instance using its default property:

src/pages/component-library.astro
---
// imports all files that end with `.astro` in `./src/components/`
const components = Object.values(import.meta.glob('../components/*.astro', { eager: true }));
---
<!-- Display all of our components -->
{components.map((component) => (
<div>
<component.default size={24} />
</div>
))}

¥Supported Values

Vite 的 import.meta.glob() 函数仅支持静态字符串字面量。它不支持动态变量和字符串插值。

¥Vite’s import.meta.glob() function only supports static string literals. It does not support dynamic variables and string interpolation.

一种常见的解决方法是导入包含所有所需文件的更大文件集,然后过滤它们:

¥A common workaround is to instead import a larger set of files that includes all the files you need, then filter them:

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>
Take a look at my favorite post, <a href={myFeaturedPost.url}>{myFeaturedPost.frontmatter.title}</a>!
</p>

¥Import type utilities

¥Markdown files

使用 import.meta.glob() 加载的 Markdown 文件返回以下 MarkdownInstance 接口:

¥Markdown files loaded with import.meta.glob() return the following MarkdownInstance interface:

export interface MarkdownInstance<T extends Record<string, any>> {
/* Any data specified in this file's YAML frontmatter */
frontmatter: T;
/* The absolute file path of this file */
file: string;
/* The rendered path of this file */
url: string | undefined;
/* Astro Component that renders the contents of this file */
Content: AstroComponentFactory;
/** (Markdown only) Raw Markdown file content, excluding layout HTML and YAML frontmatter */
rawContent(): string;
/** (Markdown only) Markdown file compiled to HTML, excluding layout HTML */
compiledContent(): string;
/* Function that returns an array of the h1...h6 elements in this file */
getHeadings(): Promise<{ depth: number; slug: string; text: string }[]>;
default: AstroComponentFactory;
}

你可以选择使用 TypeScript 泛型为 frontmatter 变量提供类型。

¥You can optionally provide a type for the frontmatter variable using a TypeScript generic.

---
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 files

Astro 文件具有以下接口:

¥Astro files have the following interface:

export interface AstroInstance {
/* The file path of this file */
file: string;
/* The URL for this file (if it is in the pages directory) */
url: string | undefined;
default: AstroComponentFactory;
}

¥Other files

其他文件可能有各种不同的接口,但如果你确切知道无法识别的文件类型包含什么内容,import.meta.glob() 就会接受 TypeScript 泛型。

¥Other files may have various different interfaces, but import.meta.glob() accepts a TypeScript generic if you know exactly what an unrecognized file type contains.

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

¥Glob Patterns

glob 模式是支持特殊通配符的文件路径。这用于一次引用项目中的多个文件。

¥A glob pattern is a file path that supports special wildcard characters. This is used to reference multiple files in your project at once.

例如,通配符模式 ./pages/**/*.{md,mdx} 在 Pages 子目录中开始,查找其所有子目录 (/**),并匹配以 .md.mdx (.{md,mdx}) 结尾的任何文件名 (/*)。

¥For example, the glob pattern ./pages/**/*.{md,mdx} starts within the pages subdirectory, looks through all of its subdirectories (/**), and matches any filename (/*) that ends in either .md or .mdx (.{md,mdx}).

Astro 中的通配符模式

标题部分 Astro 中的通配符模式

¥Glob Patterns in Astro

要与 import.meta.glob() 一起使用,glob 模式必须是字符串字面量并且不能包含任何变量。

¥To use with import.meta.glob(), the glob pattern must be a string literal and cannot contain any variables.

此外,通配符模式必须以以下之一开头:

¥Additionally, glob patterns must begin with one of the following:

  • ./(从当前目录开始)

  • ../(从父目录开始)

  • /(从项目的根目录开始)

阅读有关 glob 模式语法的更多信息

¥Read more about the glob pattern syntax.

import.meta.glob()getCollection()

标题部分 import.meta.glob() 与 getCollection()

¥import.meta.glob() vs getCollection()

Content collections provide a getCollection() API for loading multiple files instead of import.meta.glob(). If your content files (e.g. Markdown, MDX, Markdoc) are located in collections within the src/content/ directory, use getCollection() to query a collection 并返回内容条目。

¥Content collections provide a getCollection() API for loading multiple files instead of import.meta.glob(). If your content files (e.g. Markdown, MDX, Markdoc) are located in collections within the src/content/ directory, use getCollection() to query a collection and return content entries.

// Loads and initializes the requested WASM file
const wasm = await WebAssembly.instantiateStreaming(fetch('/example.wasm'));

Astro 支持使用浏览器的 WebAssembly API 将 WASM 文件直接加载到你的应用中。

¥Astro supports loading WASM files directly into your application using the browser’s WebAssembly API.

¥Node Builtins

我们鼓励 Astro 用户尽可能避免使用 Node.js 内置程序(fspath 等)。Astro 使用 adapters 与多个运行时兼容。这包括 DenoCloudflare Workers,它们不支持 Node 内置模块,例如 fs

¥We encourage Astro users to avoid Node.js builtins (fs, path, etc.) whenever possible. Astro is compatible with multiple runtimes using adapters. This includes Deno and Cloudflare Workers which do not support Node builtin modules such as fs.

我们的目标是为常见的 Node.js 内置函数提供 Astro 替代品。然而,今天不存在这样的替代方案。因此,如果你确实需要使用这些内置模块,我们不想阻止你。Astro 使用 Node 较新的 node: 前缀支持 Node.js 内置程序。例如,如果你想读取一个文件,你可以这样做:

¥Our aim is to provide Astro alternatives to common Node.js builtins. However, no such alternatives exist today. So, if you really need to use these builtin modules we don’t want to stop you. Astro supports Node.js builtins using Node’s newer node: prefix. If you want to read a file, for example, you can do so like this:

src/components/MyComponent.astro
---
// Example: import the "fs/promises" builtin from Node.js
import fs from 'node:fs/promises';
const url = new URL('../../package.json', import.meta.url);
const json = await fs.readFile(url, 'utf-8');
const data = JSON.parse(json);
---
<span>Version: {data.version}</span>

¥Extending file type support

使用 Vite 和兼容的 Rollup 插件,你可以导入 Astro 本身不支持的文件类型。在 Vite 文档的 寻找插件 部分了解在哪里可以找到你需要的插件。

¥With Vite and compatible Rollup plugins, you can import file types which aren’t natively supported by Astro. Learn where to find the plugins you need in the Finding Plugins section of the Vite Documentation.

Astro 中文网 - 粤ICP备13048890号