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 集成 并使用 .mdx 文件。

¥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 and use .mdx files in your project.

¥Files in public/

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

¥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. You can reference a public/ file by a URL path directly in your HTML templates.

¥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 hoisted 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.

¥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.

¥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.

Astro.glob() 是一种一次导入多个文件的方法。

¥Astro.glob() is a way to import many files at once.

Astro.glob() 仅采用一个参数:与你要导入的本地文件匹配的相对 通配符模式。它是异步的,并返回每个匹配文件的导出的数组。

¥Astro.glob() only takes one parameter: a relative glob pattern matching the local files you’d like to import. It’s asynchronous, and returns an array of each matching file’s exports.

src/components/my-component.astro
---
// imports all files that end with `.md` in `./src/pages/post/`
const posts = await Astro.glob('../pages/post/*.md');
---
<!-- 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>

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

¥Astro components imported using Astro.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 = await Astro.glob('../components/*.astro');
---
<!-- Display all of our components -->
{components.map((component) => (
<div>
<component.default size={24} />
</div>
))}

¥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}).

¥Glob Patterns in Astro

要与 Astro.glob() 一起使用,glob 模式必须是字符串字面量并且不能包含任何变量。请参阅 故障排除指南 了解解决方法。

¥To use with Astro.glob(), the glob pattern must be a string literal and cannot contain any variables. See the troubleshooting guide for a workaround.

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

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

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

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

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

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

¥Read more about the glob pattern syntax.

Astro.glob()getCollection()

Section titled Astro.glob() 与 getCollection()

¥Astro.glob() vs getCollection()

内容集合 提供了 getCollection() API 来加载多个文件,而不是 Astro.glob()。如果你的内容文件(例如 Markdown、MDX、Markdoc)位于 src/content/ 目录内的集合中,请使用 getCollection()查询集合 并返回内容条目。

¥Content collections provide a getCollection() API for loading multiple files instead of Astro.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号