zy-react-data/rollup.config.js

140 lines
3.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import { readFileSync, existsSync } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { glob } from 'glob';
// 获取当前文件所在目录的绝对路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
/**
* 收集所有的入口文件
*
* 遍历 enum 目录,查找所有 .js 文件作为打包入口
* 注意json 目录被排除,因为 JSON 文件直接复制,不作为入口处理
*
* @returns {Object} 入口文件对象,格式:{ 'enum/dictionary/index.js': '/absolute/path/enum/dictionary/index.js' }
*/
function getEntryFiles() {
const entries = {};
const baseDir = __dirname;
const srcDir = path.join(baseDir, 'src');
// 只处理枚举目录JSON 文件直接复制不转换
const dirs = ['enum'];
dirs.forEach(dir => {
const dirPath = path.join(srcDir, dir);
if (existsSync(dirPath)) {
// 递归查找当前目录下所有 .js 文件
const files = glob.sync('**/*.js', {
cwd: dirPath,
absolute: false
});
// 为每个文件创建入口映射,并保留源文件目录结构
files.forEach(file => {
const key = path.join(dir, file);
entries[key] = path.join(srcDir, dir, file);
});
}
});
return entries;
}
/**
* 自定义插件:复制类型声明文件和 JSON 文件
*
* 功能:
* 1. 复制 enum 目录下的 .d.ts 类型声明文件
* 2. 复制 json 目录下的 .json 数据文件,保持原始格式
*
* 注意:所有源文件都在 src/ 目录,构建输出到根目录
*/
const copyTypesPlugin = () => ({
name: 'copy-types',
// 在生成 bundle 时执行
generateBundle() {
const srcDir = path.join(__dirname, 'src');
const enumDir = path.join(srcDir, 'enum');
const this$1 = this;
// ===== 1. 复制枚举类型声明文件 (.d.ts) =====
if (existsSync(enumDir)) {
const dtsFiles = glob.sync('**/*.d.ts', {
cwd: enumDir,
absolute: true
});
dtsFiles.forEach(file => {
const relativePath = path.relative(enumDir, file);
const content = readFileSync(file, 'utf-8');
this$1.emitFile({
type: 'asset',
fileName: path.join('enum', relativePath),
source: content
});
});
}
// ===== 2. 复制 json 文件夹(保持原始格式,不转换) =====
const jsonDir = path.join(srcDir, 'json');
if (existsSync(jsonDir)) {
const jsonFiles = glob.sync('**/*.json', {
cwd: jsonDir,
absolute: true
});
jsonFiles.forEach(file => {
const relativePath = path.relative(jsonDir, file);
const content = readFileSync(file, 'utf-8');
this$1.emitFile({
type: 'asset',
fileName: path.join('json', relativePath),
source: content
});
});
}
}
});
/**
* 创建 Rollup 配置的辅助函数
*
* @param {string} outputDir - 输出目录
* @param {string} format - 输出格式('esm' 或 'cjs'
* @param {Array} plugins - 插件列表
* @returns {Object} Rollup 配置对象
*/
function createConfig(outputDir, format, plugins) {
return {
// 入口文件对象
input: getEntryFiles(),
// 输出配置
output: {
dir: outputDir,
format: format,
preserveModules: true,
preserveModulesRoot: './',
entryFileNames: '[name]',
exports: 'named'
},
// 插件列表
plugins
};
}
/**
* 导出配置
*
* 只输出 ESM 格式到根目录enum/、json/
*/
export default createConfig('.', 'esm', [copyTypesPlugin()]);