vite: 使用 yml 放项目中作为 db

在项目中有不少的静态数据,可以放在 yml 中统一管理

01 初始化一个 vite + react 项目

yarn create vite . --template react-ts

02 安装 vite 插件

安装插件

yarn add --dev @modyfi/vite-plugin-yaml

03 配置 vite.config.ts

配置文件

// vite.config.js / vite.config.ts
import ViteYaml from '@modyfi/vite-plugin-yaml';

export default {
  plugins: [
    ViteYaml(), // you may configure the plugin by passing in an object with the options listed below
  ],
};

04 针对 yml 格式兼容 ts 提示

这个如果不处理 xx.yml 导入时会有红色的提示

// vite-env.d.ts
/// <reference types="@modyfi/vite-plugin-yaml/modules" />

05 项目中使用

文件位置为  data/db1.yml

导入 yml 为项目中的数据

import db1 from "./data/db1.yml";
import db2 from "./data/db2.yml";
export default function App() {
  console.log("db1: ", db1);
  console.log("db2: ", db2);

  return (
    <div className="debug container mx-auto my-10 bg-gray-200 p-5" data-role="app-container">
      <code>
        <pre>{JSON.stringify(db1, null, 2)}</pre>
      </code>
      <hr />
      <code>
        <pre>{JSON.stringify(db2, null, 2)}</pre>
      </code>
    </div>
  );
}

预览效果

vite yml plugin data