Skip to content

Commit

Permalink
feat: allow to provide custom index.js template (#378)
Browse files Browse the repository at this point in the history
New index.js generator does not cover my cases.

1. need to add `// @flow` on top of the file
2. need to use named export

Both can be easily solved with indexTemplate option.

```
function indexTemplate(files) {
  const exportEntries = files.map(file => {
    const basename = path.basename(file, path.extname(file))
    return `export { ${basename} } from './${basename}'`
  })
  return '// @flow\n' + exportEntries.join('\n')
}

```
  • Loading branch information
TrySound authored and gregberge committed Jan 17, 2020
1 parent 61a7ddb commit f734dda
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 6 deletions.
11 changes: 11 additions & 0 deletions __fixtures__/custom-index-template.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const path = require('path')

function indexTemplate(files) {
const exportEntries = files.map(file => {
const basename = path.basename(file, path.extname(file))
return `export { ${basename} } from './${basename}'`
})
return exportEntries.join('\n')
}

module.exports = indexTemplate
18 changes: 18 additions & 0 deletions __fixtures__/custom-index.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const indexTemplate = require('./custom-index-template.js')

function template(
{ template },
opts,
{ imports, componentName, props, jsx, exports },
) {
return template.ast`${imports}
export function ${componentName}(${props}) {
return ${jsx};
}
`
}

module.exports = {
template,
indexTemplate,
}
4 changes: 4 additions & 0 deletions packages/cli/src/__snapshots__/index.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export default SvgFile;
"
`;

exports[`cli should support --index-template in cli 1`] = `"export { File } from './File'"`;

exports[`cli should support --prettier-config as file 1`] = `
"import React from 'react'
Expand Down Expand Up @@ -84,6 +86,8 @@ Array [
]
`;

exports[`cli should support custom index.js with directory output 1`] = `"export { File } from './File'"`;

exports[`cli should support different filename cases with directory output 1`] = `
Array [
"CamelCase.js",
Expand Down
17 changes: 12 additions & 5 deletions packages/cli/src/dirCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { promisify } from 'util'
import path from 'path'
import chalk from 'chalk'
import outputFileSync from 'output-file-sync'
import { loadConfig } from '@svgr/core'
import { convertFile, stat, transformFilename, CASE, politeWrite } from './util'

const access = promisify(fs.access)
Expand Down Expand Up @@ -34,6 +35,14 @@ export function isCompilable(filename) {
return COMPILABLE_EXTENSIONS.includes(ext)
}

function defaultIndexTemplate(files) {
const exportEntries = files.map(file => {
const basename = path.basename(file, path.extname(file))
return `export { default as ${basename} } from './${basename}'`
})
return exportEntries.join('\n')
}

export default async function dirCommand(
program,
filenames,
Expand All @@ -59,11 +68,9 @@ export default async function dirCommand(

async function generateIndex(dest, files) {
const indexFile = path.join(dest, `index.${ext}`)
const exportEntries = files.map(file => {
const basename = path.basename(file, path.extname(file))
return `export { default as ${basename} } from './${basename}'`
})
fs.writeFileSync(indexFile, exportEntries.join('\n'))
const config = loadConfig.sync(options, { filePath: indexFile })
const indexTemplate = config.indexTemplate || defaultIndexTemplate
fs.writeFileSync(indexFile, indexTemplate(files))
}

async function handle(filename, root) {
Expand Down
28 changes: 27 additions & 1 deletion packages/cli/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ program
parseObjectList,
)
.option('--template <file>', 'specify a custom template to use')
.option(
'--index-template <file>',
'specify a custom index.js template to use',
)
.option('--title-prop', 'create a title element linked with props')
.option(
'--prettier-config <fileOrJson>',
Expand Down Expand Up @@ -146,7 +150,8 @@ async function run() {

if (config.template) {
try {
const template = require(path.join(process.cwd(), program.template)) // eslint-disable-line global-require, import/no-dynamic-require
// eslint-disable-next-line global-require, import/no-dynamic-require
const template = require(path.join(process.cwd(), program.template))
if (template.default) config.template = template.default
else config.template = template

Expand All @@ -159,6 +164,27 @@ async function run() {
}
}

if (config.indexTemplate) {
try {
// eslint-disable-next-line global-require, import/no-dynamic-require
const indexTemplate = require(path.join(
process.cwd(),
program.indexTemplate,
))
if (indexTemplate.default) config.indexTemplate = indexTemplate.default
else config.indexTemplate = indexTemplate

if (typeof config.indexTemplate !== 'function')
throw new Error('indexTemplate must be a function')
} catch (error) {
console.error(
`Error when loading indexTemplate: ${program.indexTemplate}\n`,
)
console.error(error.stack)
process.exit(2)
}
}

const command = program.outDir ? dirCommand : fileCommand
await command(program, filenames, config)
}
Expand Down
18 changes: 18 additions & 0 deletions packages/cli/src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,4 +166,22 @@ describe('cli', () => {
)
expect(result).toMatchSnapshot()
}, 10000)

it('should support custom index.js with directory output', async () => {
const inDir = '__fixtures__/simple'
const outDir = `__fixtures_build__/custom-index`
await del(outDir)
await cli(`${inDir} --out-dir=${outDir} --config-file=__fixtures__/custom-index.config.js`)
const content = fs.readFileSync(path.join(outDir, 'index.js'), 'utf-8')
expect(content).toMatchSnapshot()
}, 10000)

it('should support --index-template in cli', async () => {
const inDir = '__fixtures__/simple'
const outDir = `__fixtures_build__/custom-index-arg`
await del(outDir)
await cli(`${inDir} --out-dir=${outDir} --index-template=__fixtures__/custom-index-template.js`)
const content = fs.readFileSync(path.join(outDir, 'index.js'), 'utf-8')
expect(content).toMatchSnapshot()
}, 10000)
})
9 changes: 9 additions & 0 deletions website/src/pages/docs/options.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,15 @@ Output files into a directory.
| ----------- | --------------------- | --------------------- |
| `undefined` | `--out-dir <dirname>` | Only available in CLI |

## index.js template

Specify a template function (API) to change default index.js output (when --out-dir is used).

| Default | CLI Override | API Override |
| ------------------ | ------------------ | -------------------------- |
| [`basic template`](https://github.com/gregberge/svgr/blob/master/packages/cli/src/dirCommand.js) | `--index-template` | indexTemplate: files => '' |


## Keep existing

When used with `--out-dir`, it does not override already existing files.
Expand Down

1 comment on commit f734dda

@vercel
Copy link

@vercel vercel bot commented on f734dda Jan 17, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.