inline-schema/csv-loader.md

2.8 KiB
Raw Blame History

inline-schema/csv-loader

A rspack loader for CSV files that uses inline-schema for type validation.

Installation

npm install inline-schema

Usage

The loader expects:

  • First row: Property names (headers)
  • Second row: Inline-schema definitions for each property
  • Remaining rows: Data values

Example CSV

name,age,active,scores
string,number,boolean,number[]
Alice,30,true,[90; 85; 95]
Bob,25,false,[75; 80; 70]

rspack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.schema\.csv$/,
        use: {
          loader: 'inline-schema/csv-loader',
          options: {
            delimiter: ',',
            quote: '"',
            escape: '\\',
            bom: true,        // 处理 BOM (默认 true)
            comment: '#',     // 忽略 # 开头的注释行 (默认 '#')
            trim: true,       // 修剪表头和值的前后空格 (默认 true)
            // emitTypes: false, // 禁用类型定义生成 (默认 true)
            // typesOutputDir: 'types', // 类型文件输出目录 (可选)
          },
        },
      },
    ],
  },
};

Generated TypeScript Types

emitTypes: trueloader 会自动生成 .d.ts 类型定义文件:

// data.schema.d.ts
declare module "./data.schema.csv" {
  export interface data_schema {
    name: string;
    age: number;
    active: boolean;
    scores: number[];
  }

  export type RowType = data_schema;

  const data: data_schema[];
  export default data;
}

Importing in TypeScript

import data from './data.schema.csv';

// TypeScript 会自动推断类型:
// data: { name: string; age: number; active: boolean; scores: number[] }[]

// 如果启用了 emitTypes也可以显式导入类型:
import type { RowType } from './data.schema.csv';

Options

Option Type Default Description
delimiter string , Column delimiter
quote string " Quote character
escape string \ Escape character
bom boolean true Handle byte order mark
comment string | false # Comment character (set false to disable)
trim boolean true Trim headers and values
emitTypes boolean true Generate TypeScript declaration file (.d.ts)
typesOutputDir string '' Output directory for generated type files (relative to output path)

Schema Syntax

Uses inline-schema syntax:

Type Schema Example
String string hello
Number number 42
Boolean boolean true
Array string[] or [string][] [a; b; c]
Tuple [string; number] [hello; 42]

License

ISC