安装 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 --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 // Specify the file extension you want to importdeclare module "*.yml" {const value: any; // Add type definitions here if desiredexport default value;}这将使你的编辑器能够为你的 YAML 数据提供类型提示。