From 82928f02e4a2ae1160e54884461f9edde4ad2293 Mon Sep 17 00:00:00 2001 From: Enrico Balsamo Date: Sun, 14 May 2023 21:52:39 +0200 Subject: [PATCH] docs: 858 Index template docs improvements (#872) --- website/pages/docs/cli.mdx | 2 +- website/pages/docs/custom-templates.mdx | 38 ++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/website/pages/docs/cli.mdx b/website/pages/docs/cli.mdx index 7eed27d5..af3bf2ae 100644 --- a/website/pages/docs/cli.mdx +++ b/website/pages/docs/cli.mdx @@ -99,7 +99,7 @@ Advanced use cases could lead you to customize the index template. The `--index- const path = require('path') function defaultIndexTemplate(filePaths) { - const exportEntries = filePaths.map(({ path: filePath }) => { + const exportEntries = filePaths.map(({ path: filePath, originalPath }) => { const basename = path.basename(filePath, path.extname(filePath)) const exportName = /^\d/.test(basename) ? `Svg${basename}` : basename return `export { default as ${exportName} } from './${basename}'` diff --git a/website/pages/docs/custom-templates.mdx b/website/pages/docs/custom-templates.mdx index 43d4f757..6184aff6 100644 --- a/website/pages/docs/custom-templates.mdx +++ b/website/pages/docs/custom-templates.mdx @@ -99,7 +99,12 @@ module.exports = { When you use the CLI with `--out-dir` option, an index file is automatically generated. -The customization is the same, a file that exports a function: +The customization is the same, a file that exports a function. The function receives an argument that is an array containing objects made of the original file path and the path of the file containing the generated React component: + +- `originalPath`: the original file's path +- `path`: the React component's file's path + +Default template only uses `path` and it is similar to this: ```js const path = require('path') @@ -116,6 +121,37 @@ function defaultIndexTemplate(filePaths) { module.exports = defaultIndexTemplate ``` +but you could implement a more advanced template exploiting the original file name too: + +```js +const path = require('path') + +function defaultIndexTemplate(filePaths) { + const entries = filePaths.map(({ path: filePath, originalPath }) => { + const originalFileName = path.basename( + originalPath, + path.extname(originalPath), + ) + 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(({ importLine }) => importLine).join('\n')} +export const map = { +${entries.map(({ mapLine }) => mapLine).join(',\n')} +} +` +} + +module.exports = defaultIndexTemplate +``` + ### Use with CLI You can use component template in the CLI: