Skip to content

svgr-cli: Make index template receive both created fileNames and original icon files' names #858

@balsick

Description

@balsick

🚀 Feature Proposal

Make custom index template receive both the created files' names and the original icon files' names

Motivation

You could need to create an object into your index.{ext} containing the mapping between the original svg icons' strings and the React component, e.g. when some APIs indicate you what icon should be used by its name.

Example

If just the parameter was added to the template function, you could generate the index like this:

const path = require('path')

function defaultIndexTemplate(filePaths, originalFileNames) {
  const entries = filePaths.map((filePath, index) => {
    const originalFileName = originalFileNames[index].replace(/\.svg$/, '')
    const basename = path.basename(filePath, path.extname(filePath))
    const exportName = /^\d/.test(basename) ? `Svg${basename}` : basename
    const importLine = `import ${exportName} from './${basename}';`
    const mapLine = `${/.*[.-].*/.test(originalFileName) ? `'${originalFileName}'` : originalFileName}: ${exportName}`
    return [importLine, mapLine]
  })
  return `${entries.map(([e]) => e).join('\n')}
export const map = {
${entries.map(([, e]) => e).join(',\n')}
}
`
}

module.exports = defaultIndexTemplate

Pitch

This improvement could let people generate their own npm scripts with more flexibility and could let them use them every time a new icon is added without having to operate manually.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions