专业编程基础技术教程

网站首页 > 基础教程 正文

【JS 导出公共组件】使用脚本文件自动导出公共组件

ccvgpt 2025-01-10 11:58:29 基础教程 13 ℃

最近在维护一个项目,发现公共组件都是一个个导出引入的,因此写了一个脚本文件将组件自动写入index.ts文件内,之后统一引用即可

使用前

【JS 导出公共组件】使用脚本文件自动导出公共组件

import OACard from '@/components/common/OACard';
import OAInput from '@/components/common/OAInput';
import OASwitch from '@/components/common/OASwitch';
import OASelect from '@/components/common/OASelect';
import OATextarea from '@/components/common/OATextarea';

使用后

import { OAInput, OASwitch, OACard, OASelect, OATextarea } from '@/components/common';

代码如下

const fs = require('fs');
const path = require('path');

// 定义组件目录和导出文件的路径
const componentsDir = path.join(__dirname, '../src/components/common');
const exportFile = path.join(componentsDir, 'index.ts');

// 检查文件是否存在
const export_exists = fs.existsSync(exportFile);

//获取导出文件内容
let exportFileContent = ''
if(export_exists){
  exportFileContent = fs.readFileSync(exportFile, 'utf-8');
}

// 获取组件目录下的所有文件
const files = fs.readdirSync(componentsDir);

// 过滤出 .tsx 文件
const tsxFiles = files.filter(file => path.extname(file) === '.tsx');

// 生成导出语句
const newStatements = []
for(let i=0;i<tsxFiles.length;i++){
    const componentName = path.basename(tsxFiles[i], '.tsx');
    //有些文件是以'-'拼接,需要特殊处理
    const name = componentName.replace('-', '')
    const impPath = `'./${componentName}';`;
   //已经导出的组件不再重复导出
    if(export_exists && exportFileContent.includes(impPath)) {
        console.log(`组件 ${componentName} 已存在于导出文件中,跳过导出。`);
        continue
    }
   //约定OA开头才是公共组件
    if(!name.startsWith('OA')){
        continue
    }
    console.log('impPath',impPath)
    newStatements.push(`export { default as ${name} } from ${impPath}`)
}


const exportStatements = exportFileContent + '\n' + newStatements.join('\n');

// 将导出语句写入导出文件
fs.writeFileSync(exportFile, exportStatements);

console.log(`Components exported successfully to: ${exportFile}`);

上述代码加了后续添加组件时,之前代码不变动的逻辑,方便执行脚本之后内容还可以自定义配置。

Tags:

最近发表
标签列表