Extract CSS From SVG and move it to seperate file

mkdir your-project-directory
cd your-project-directory
mkdir svgs

npm init -y
npm install xmldom
touch script_name.js

const fs = require('fs');
const path = require('path');
const { DOMParser, XMLSerializer } = require('xmldom');

// Function to generate unique class names
let classCounter = 0;
const generateClassName = () => `svg-class-${classCounter++}`;

// Function to convert SVG styles to classes and return the modified SVG and extracted CSS
function convertSVGStylesToClasses(svgString, uniqueSuffix) {
  const parser = new DOMParser();
  const svgDoc = parser.parseFromString(svgString, "image/svg+xml");

  let styles = "";
  let index = 0;

  traverseNodes(svgDoc.documentElement);
  extractStyleElements(svgDoc);

  const modifiedSVG = new XMLSerializer().serializeToString(svgDoc);
  return { svg: modifiedSVG, css: styles };

  function traverseNodes(node) {
    if (node.nodeType === 1) { // Element node
      const attributes = ["fill", "stroke", "stroke-width"];
      let style = "";
      let hasStyle = false;

      attributes.forEach(attr => {
        if (node.hasAttribute(attr)) {
          style += `${attr}: ${node.getAttribute(attr)}; `;
          node.removeAttribute(attr);
          hasStyle = true;
        }
      });

      if (node.hasAttribute('style')) {
        const inlineStyle = node.getAttribute('style');
        style += `${inlineStyle} `;
        node.removeAttribute('style');
        hasStyle = true;
      }

      if (hasStyle) {
        const className = `svg-class-${uniqueSuffix}-${index++}`;
        node.setAttribute("class", className);
        styles += `.${className} { ${style} }n`;
      }
    }

    // Recursively traverse child nodes
    for (let child = node.firstChild; child; child = child.nextSibling) {
      traverseNodes(child);
    }
  }

  function extractStyleElements(svgDoc) {
    const styleElements = svgDoc.getElementsByTagName('style');
    for (let i = 0; i < styleElements.length; i++) {
      styleElements[i].parentNode.removeChild(styleElements[i]);
    }
  }
}

// Function to process SVG files in a directory and save processed files in another directory
function processSVGFiles(inputDirectory, outputDirectory) {
  const files = fs.readdirSync(inputDirectory).filter(file => path.extname(file) === '.svg');
  let combinedStyles = "";

  files.forEach((file, fileIndex) => {
    const filePath = path.join(inputDirectory, file);
    const svgContent = fs.readFileSync(filePath, 'utf-8');

    const uniqueSuffix = `file${fileIndex}`;
    const { svg: modifiedSVG, css } = convertSVGStylesToClasses(svgContent, uniqueSuffix);
    combinedStyles += css;

    const outputFilePath = path.join(outputDirectory, file); // Use original filename
    fs.writeFileSync(outputFilePath, modifiedSVG, 'utf-8');
    console.log(`Processed ${file}`);
  });

  const cssFilePath = path.join(outputDirectory, 'combined_styles.css');
  fs.writeFileSync(cssFilePath, combinedStyles, 'utf-8');
  console.log(`Combined styles written to ${cssFilePath}`);
}

// Specify the input and output directories
const inputDirectory = './svgs';
const outputDirectory = './processed_svgs';

// Create the output directory if it doesn't exist
if (!fs.existsSync(outputDirectory)) {
  fs.mkdirSync(outputDirectory);
}

// Process SVG files from inputDirectory and save processed files to outputDirectory
processSVGFiles(inputDirectory, outputDirectory);

your-project-directory/

├── svgs/
│ ├── svg1.svg
│ ├── svg2.svg
│ ├── svg3.svg
│ └── … (your other SVG files)

├── node_modules/
│ └── … (generated after running npm install)

├── package.json

├── script_name.js

└── combined_styles.css (generated by the script)

Please check If this work or not

tried several ways for

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật