Skip to content

Commit

Permalink
fix: ensure a valid name for exports (#489)
Browse files Browse the repository at this point in the history
Co-authored-by: Endika Intxaurtieta <endika@MacBook-Pro-de-Endika.local>
  • Loading branch information
eintxaurtieta and Endika Intxaurtieta committed Nov 15, 2020
1 parent 16a58d6 commit 0eb8085
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
10 changes: 8 additions & 2 deletions packages/cli/src/dirCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ import { promises as fs } from 'fs'
import path from 'path'
import chalk from 'chalk'
import { loadConfig } from '@svgr/core'
import { convertFile, transformFilename, CASE, politeWrite } from './util'
import {
convertFile,
transformFilename,
CASE,
politeWrite,
formatExportName,
} from './util'

async function exists(file) {
try {
Expand Down Expand Up @@ -33,7 +39,7 @@ export function isCompilable(filename) {
function defaultIndexTemplate(filePaths) {
const exportEntries = filePaths.map((filePath) => {
const basename = path.basename(filePath, path.extname(filePath))
const exportName = /^\d/.test(basename) ? `Svg${basename}` : basename
const exportName = formatExportName(basename)
return `export { default as ${exportName} } from './${basename}'`
})
return exportEntries.join('\n')
Expand Down
16 changes: 16 additions & 0 deletions packages/cli/src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,19 @@ export function politeWrite(program, data) {
process.stdout.write(data)
}
}

export function formatExportName(name) {
if (/[-]/g.test(name) && /^\d/.test(name)) {
return `Svg${camelcase(name, { pascalCase: true })}`
}

if (/^\d/.test(name)) {
return `Svg${name}`
}

if (/[-]/g.test(name)) {
return camelcase(name, { pascalCase: true })
}

return name
}
10 changes: 9 additions & 1 deletion packages/cli/src/util.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import path from 'path'
import { convertFile, transformFilename, CASE } from './util'
import { convertFile, transformFilename, CASE, formatExportName } from './util'

const FIXTURES = path.join(__dirname, '../../../__fixtures__')

Expand Down Expand Up @@ -31,4 +31,12 @@ describe('util', () => {
expect(transformFilename('foo_bar', CASE.PASCAL)).toBe('FooBar')
})
})

describe('#formatExportName', () => {
it('should ensure a valid export name', () => {
expect(formatExportName('foo-bar')).toBe('FooBar')
expect(formatExportName('2foo')).toBe('Svg2foo')
expect(formatExportName('2foo-bar')).toBe('Svg2FooBar')
})
})
})

1 comment on commit 0eb8085

@vercel
Copy link

@vercel vercel bot commented on 0eb8085 Nov 15, 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.