refactor: reorg/remove webpack dependency

This commit is contained in:
2026-04-07 11:25:02 +08:00
parent 77ee96d70c
commit ad38976e86
5 changed files with 125 additions and 91 deletions
+3 -53
View File
@@ -1,9 +1,6 @@
import type { LoaderContext } from '@rspack/core';
import { parse } from 'csv-parse/sync';
import { parseSchema, createValidator, parseValue } from '../index.js';
import type { Schema } from '../types.js';
import * as path from 'path';
import * as fs from 'fs';
export interface CsvLoaderOptions {
delimiter?: string;
@@ -184,7 +181,7 @@ export function parseCsv(
/**
* Generate JavaScript module code from CSV content.
* Returns a string that can be used as a module export.
*
*
* @param content - CSV content string
* @param options - Parsing options
* @returns JavaScript module code string
@@ -194,59 +191,12 @@ export function csvToModule(
options: CsvLoaderOptions & { resourceName?: string } = {}
): { js: string; dts?: string } {
const result = parseCsv(content, options);
const json = JSON.stringify(result.data, null, 2);
const js = `export default ${json};`;
return {
js,
dts: result.typeDefinition,
};
}
export default function csvLoader(
this: LoaderContext<CsvLoaderOptions>,
content: string
): string | Buffer {
const options = this.getOptions() as CsvLoaderOptions | undefined;
const emitTypes = options?.emitTypes ?? true;
const typesOutputDir = options?.typesOutputDir ?? '';
const writeToDisk = options?.writeToDisk ?? false;
// Infer resource name from filename
const fileName = path.basename(this.resourcePath, '.csv').split('.')[0];
const resourceName = fileName
.replace(/[-_\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : '')
.replace(/^(.)/, (_, char) => char.toUpperCase());
const result = parseCsv(content, { ...options, resourceName });
// Emit type definition file if enabled
if (emitTypes && result.typeDefinition) {
const context = this.context || '';
// Get relative path from context, normalize to forward slashes
let relativePath = this.resourcePath.replace(context, '');
if (relativePath.startsWith('\\') || relativePath.startsWith('/')) {
relativePath = relativePath.substring(1);
}
relativePath = relativePath.replace(/\\/g, '/');
// Replace .csv with .csv.d.ts for the output filename
const dtsFileName = `${relativePath}.d.ts`;
const outputPath = typesOutputDir
? path.join(typesOutputDir, dtsFileName)
: dtsFileName;
if (writeToDisk) {
// Write directly to disk (useful for dev server)
const absolutePath = path.join(this.context || process.cwd(), typesOutputDir || '', dtsFileName);
fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
fs.writeFileSync(absolutePath, result.typeDefinition);
} else {
// Emit to in-memory filesystem (for production build)
this.emitFile?.(outputPath, result.typeDefinition);
}
}
return `export default ${JSON.stringify(result.data, null, 2)};`;
}