Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
// Validate color attributes
['stroke', 'fill'].forEach(attr => {
const color = $el.attr(attr);
const validColors = ['currentColor', 'none', '#000'];
if (color && !validColors.includes(color)) {
throw new Error(`${svgName}: Invalid ${attr} color: ${$.html(el)}`);
}
});
});
const iconName = `Icon${pascalCase(svgName)}`;
const svgComponentName = `${iconName}${
variantName ? pascalCase(variantName) : ''
}Svg`;
const svgComponent = await svgr(optimisedSvg, svgrConfig, {
componentName: svgComponentName,
});
// Create icon directory if it's missing
const iconDir = path.join(iconComponentsDir, iconName);
await fs.mkdirp(iconDir);
// Write SVG React component
await fs.writeFile(
path.join(iconDir, `${svgComponentName}.tsx`),
svgComponent,
{ encoding: 'utf-8' },
);
// Bail out early if we're processing an icon variant (e.g. bookmark-active.svg)
// All subsequent steps should only happen once per icon component.
console.log(chalk.green(`[Generate SVG Component] Icon Amount: ${svgFileNames.length}`));
const componentNames = [];
const metaData = {};
const mirrorMetaData = {};
for (const svgPath of svgFilePaths) {
const svgCode = fs.readFileSync(svgPath);
const svgName = `${getComponentName({ filePath: svgPath })}`;
componentNames.push(svgName);
const kebabcaseName = kebabcase(svgName);
metaData[kebabcaseName] = svgName;
mirrorMetaData[svgName] = kebabcaseName;
if (shouldGenerateReactComponent) {
const componentCode = await svgr(svgCode, svgrConfig, { filePath: svgPath });
fs.writeFileSync(path.resolve(OUTPUT_DIR, `${svgName}.tsx`), componentCode);
}
}
if (shouldGenerateReactComponent) {
console.log(chalk.green(`[Generate SVG Component] Icon Components Generated!`));
}
fs.writeFileSync(OUTPUT_INDEX,
fs.readFileSync(path.resolve(__dirname, './index.ts.template'), { encoding: 'utf8' })
.replace('<% EXPORT_ALL_REACT_COMPONENTS %>', shouldGenerateReactComponent ? componentNames.map((name) => `export { default as ${name} } from './components/${name}';`).join('\n') : '')
);
console.log(chalk.green(`[Generate SVG Component] Entry Generated!`));
function createJs(file, component) {
const svgFile = fs.readFileSync(file, 'utf-8');
return svgr.default(
svgFile,
//this is where the rendered React component is customized:
unDrawConfig,
{ componentName: component }
)
.then (jsxFile => {
fs.writeFileSync(`${path}${component}/${component}.js`, jsxFile);
console.log(`Succesfully created component: ${component}` )
})
.catch (err => {
throw new Error("failed to generate React component, check svgr config and template")
})
}
fs.readFile(file, (err, data) => {
if (err) throw err
svgr(
data,
{
template,
expandProps: false,
removeTitle: true
},
{componentName: 'SVGComponent'}
)
.then(jsCode =>
babel.transformAsync(jsCode, {
presets: ['sui']
})
)
.then(result => {
fs.outputFile(getLibFile(file), result.code, function(error) {
if (error) {
iconFiles.forEach(async filePath => {
const svgSource = fs.readFileSync(filePath);
try {
const viewBoxPosition = svgSource.toString().indexOf('viewBox');
if (viewBoxPosition === -1) {
throw new Error(`${filePath} is missing a 'viewBox' attribute`);
}
const jsxSource = await svgr(
svgSource,
{
plugins: ['@svgr/plugin-svgo', '@svgr/plugin-jsx'],
svgoConfig: {
plugins: [
{ cleanupIDs: false },
{ prefixIds: false },
{ removeViewBox: false },
],
},
svgProps: {
xmlns: 'http://www.w3.org/2000/svg',
},
titleProp: true,
template: (
{ template },
app.post('/api/svgr', bodyParser.json(), (req, res) => {
svgr(req.body.code, { ...req.body.options, plugins: [svgo, jsx, prettier] })
.then(output => {
res.send({ output })
})
.catch(error => {
res.send({ error: error.message })
})
})
illustrations.forEach(item => {
const componentName = prefix + pascalCase(item.name);
const srcPath = path.join(svgPath, item.svg);
const srcCode = fs.readFileSync(srcPath);
const destPath = path.join(dest, `${componentName}.tsx`);
promises.push(
svgr(
srcCode,
{
icon: true,
plugins: ['@svgr/plugin-svgo', '@svgr/plugin-jsx', '@svgr/plugin-prettier'],
replaceAttrValues,
svgProps,
template
},
{ componentName }
).then(ts => fs.outputFile(destPath, ts))
);
});
const groupFilesAcc = await groupFilesAccPromise;
const componentName = path.basename(file, path.extname(file));
jsxStatus.text = `Group: ${group} | File: ${componentName}`;
const jsxPath = `${jsxSourcePath}/${componentName}.js`;
const svgCode = await fs.promises.readFile(`${groupPath}/${file}`, {
encoding: "utf8",
});
const iconSizeName = componentName.substr(0, 2);
const originalSize = originalSizes[iconSizeName];
const croppedSize = croppedSizes[iconSizeName];
const margin = Math.floor((originalSize - croppedSize) / 2);
const jsxCode = await svgr(
svgCode,
{
icon: true,
replaceAttrValues: { "#2F313A": "{color}" },
svgProps: {
width: "{size}",
height: "{size}",
ref: "{ref}",
"aria-hidden": "{!props['aria-label']}",
viewBox: `${margin} ${margin} ${croppedSize} ${croppedSize}`,
},
template: jsxTemplate,
plugins: [
"@svgr/plugin-svgo",
"@svgr/plugin-jsx",
"@svgr/plugin-prettier",