Svgr: using node api without creating a module?

Created on 9 Apr 2020  ·  3Comments  ·  Source: gregberge/svgr

💬 Questions and Help

I'm trying to create a script that takes a bunch of SVGs in a directory, parses them for colors, converts every color to a prop, and exports the components.
I put this in assets/icons/vectors/svgr.js.
It is complaining that svgr isn't a function, but when I try to import it, it wants the entire package to be a module. Is there any way around this, or a better way to do this without ejecting my create-react-app?

/* eslint-disable no-param-reassign */
const svgr = require('@svgr/core');

const fs = require('fs');

console.log(svgr);
const getAllFiles = function(dirPath, arrayOfFiles) {
  const files = fs.readdirSync(dirPath);
  arrayOfFiles = arrayOfFiles || [];
  files.forEach(function(file) {
    if (fs.statSync(`${dirPath}/${file}`).isDirectory()) {
      arrayOfFiles = getAllFiles(`${dirPath}/${file}`, arrayOfFiles);
    } else if (file.match(/.svg$/)) {
      const obj = [];
      obj.data = fs.readFileSync(`${dirPath}/${file}`, 'utf8');
      obj.path = `${dirPath.split('assets/')[1]}`;
      obj.matches = [
        ...new Set(
          obj.data.match(/(?<=(fill\=")|(?<=stroke\="))(?!none)[#\w\d]+/g)
        )
      ];
      obj.replace = {};
      obj.matches.forEach(function(m, i) {
        obj.replace[m.toString()] = `props.colors[${i}]`;
      });
      arrayOfFiles[`${file}`] = obj;
    }
  });

  return arrayOfFiles;
};
const test = getAllFiles('./src/assets/vectors');
// console.log(test);
Object.keys(test).forEach(function(a) {
  svgr(
    test[a].data,
    {
      icon: true,
      plugins: [
        '@svgr/plugin-svgo',
        '@svgr/plugin-jsx',
        '@svgr/plugin-prettier'
      ],
      replaceAttrValues: test[a].replace
    },
    { componentName: 'MyComponent' }
  ).then(jsCode => {
    console.log(jsCode);
  });
});
question ❓ wontfix

Most helpful comment

Hello @AskAlice, I am sorry I don't understand your problem. Maybe you obtain something with a .default? Could you please try to be more precise?

All 3 comments

Hey @AskAlice :wave:,
Thank you for opening an issue. We'll get back to you as soon as we can.
Please, consider supporting us on Open Collective. We give a special attention to issues opened by backers.
If you use SVGR at work, you can also ask your company to sponsor us :heart:.

Hello @AskAlice, I am sorry I don't understand your problem. Maybe you obtain something with a .default? Could you please try to be more precise?

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

VincentCATILLON picture VincentCATILLON  ·  5Comments

alamothe picture alamothe  ·  6Comments

troch picture troch  ·  5Comments

gwmaster picture gwmaster  ·  4Comments

Kailash23 picture Kailash23  ·  3Comments