安装一个 Vite 或 Rollup 插件
Astro 基于 Vite 构建,并支持 Vite 和 Rollup 插件。该操作指南使用 Rollup 插件来添加在 Astro 中导入 YAML(.yml
)文件的能力。
操作步骤
- 安装
@rollup/plugin-yaml
:
npm install @rollup/plugin-yaml --save-dev
pnpm add @rollup/plugin-yaml --save-dev
yarn add @rollup/plugin-yaml --save-dev
-
在
astro.config.mjs
中导入插件并将其添加到 Vite 插件数组中:astro.config.mjs import { defineConfig } from 'astro/config';import yaml from '@rollup/plugin-yaml';export default defineConfig({vite: {plugins: [yaml()]}}); -
最后,你可以使用
import
语句导入 YAML 数据:import yml from './data.yml';当你在 Astro 项目中导入 YAML 数据时,你的编辑器将不会为导入的数据提供类型。要添加类型,请在项目的
src
目录中创建或查找现有的*.d.ts
文件,并添加以下内容:src/files.d.ts // 指定要导入的文件扩展名declare module "*.yml" {const value: any; // 添加期望的类型定义export default value;}这将允许你的编辑器为 YAML 数据提供类型提示。