Astro CSV 加载器
这个软件包为Astro提供了CSV加载器. 它允许您加载和剖析 CSV 文件,并使用您 Astro 站点中的数据,包括使用它生成页面.
安装
npm install @ascorbic/csv-loader
使用量
这个包需要Astro 4.14.0或以后. 您必须启用Astro的实验内容层, 除非您正在使用5. 0.0- beta 版本或稍后使用 。 你可以这样做,在你的 astro.config.mjs数字 :
export default defineConfig({
// ...
experimental: {
contentLayer: true,
},
});
然后可以在内容配置中使用种子加载器 :
// src/content/config.ts
import { defineCollection } from "astro:content";
import { csvLoader } from "@ascorbic/csv-loader";
const customers = defineCollection({
loader: csvLoader({
fileName: "data/customers.csv",
}),
schema: z.object({
customerID: z.number(),
firstName: z.string(),
lastName: z.string(),
email: z.string(),
age: z.number(),
registrationDate: z.coerce.date(),
purchaseAmount: z.number(),
}),
});
export const collections = { customers };
然后,您可以在Astro中像其它内容收藏一样使用这些:
---
import type { GetStaticPaths } from "astro";
import { getCollection, type CollectionEntry } from "astro:content";
import Layout from "../../layouts/Layout.astro";
export const getStaticPaths: GetStaticPaths = async () => {
const customers = await getCollection("customers");
return customers.map((customer) => ({
params: {
id: customer.id,
},
props: { customer },
}));
};
type Props = { customer: CollectionEntry<"customers"> };
const { customer } = Astro.props;
const { data } = customer;
---
<Layout title={data.firstName}>
<h1>{data.firstName} {data.lastName}</h1>
<p>{data.email}</p>
<p>{data.registrationDate.toISOString()}</p>
</Layout>
选项
这个 csvLoader 函数使用具有以下属性的选项对象:
fileName: CSV 文件要加载的路径. 这应该是绝对的,或者相对于项目根.transformHeader: 将标题值转换为字段名的函数。 默认情况下,这些值被骆驼化. 过false使数值保持不变.idField:要用作标识的字段。 本列中的值必须是独一无二的. 如果头被改变, 它就是值 之后 转变。 默认为第一列.parserOptions: 向 CSV 解析器传递了附加图案. 此天体会直接传递到PapaParse CSV库. 见 Papaparse 文档 更多信息.