index.ts 1.68 KB
import { join, resolve } from 'path';
import inquirer from 'inquirer';
import fs from 'fs-extra';
import chalk from 'chalk';

async function genreateIcon() {
  const answers = await inquirer.prompt([
    {
      type: 'input',
      name: 'entry',
      message: 'Set Iconfont.js File Entry Location!',
      default: 'src/assets/iconfont/iconfont.js',
    },
    {
      type: 'input',
      name: 'output',
      message: 'Set The Location For Storing Generated File!',
      default: 'src/components/Icon/data',
    },
    {
      type: 'outputFileName',
      name: 'outputFileName',
      message: 'Set Generate File Name!',
      default: 'iconfont.data.ts',
    },
  ]);

  const { entry, output, outputFileName } = answers;
  if (![entry, output, outputFileName].every(Boolean)) {
    global.console.log(
      `${chalk.yellow('Generate:Icon: ')}${chalk.red(
        'There is a problem with the file path you set!'
      )}`
    );
    process.exit(1);
  }

  const groupReg = /<symbol[^]*?<\/symbol>/g;
  const getIdReg = /id=(["'])(.*?)\1/;

  const string = await fs.readFileSync(resolve(process.cwd(), entry), { encoding: 'utf-8' });

  const iconNameList = Array.from(string.matchAll(groupReg)).map(([string]) => {
    const [, , name] = string.match(getIdReg) || [];
    return name.replace('iconfont-', '');
  });

  await fs.writeFileSync(
    join(output, outputFileName),
    `export default ${JSON.stringify({ prefix: 'iconfont', icons: iconNameList }, null, 2)}`
  );

  global.console.log(
    `${chalk.yellow('Generate:Icon: ')}${chalk.cyan(
      'ICon generated successfully, Store Address: '
    )}${chalk.cyan(join(resolve(process.cwd()), output, outputFileName))}`
  );
}

genreateIcon();