Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: ensure a valid name for exports #489

Merged
merged 3 commits into from
Nov 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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')
})
})
})