-
-
Notifications
You must be signed in to change notification settings - Fork 413
/
index.js
217 lines (190 loc) · 5.89 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/* eslint-disable no-console */
import program from 'commander'
import path from 'path'
import glob from 'glob'
import fs, { promises as fsPromises } from 'fs'
import { loadConfig } from '@svgr/core'
import pkg from '../package.json'
import fileCommand from './fileCommand'
import dirCommand from './dirCommand'
import { exitError } from './util'
function noUndefinedKeys(obj) {
return Object.entries(obj).reduce((obj, [key, value]) => {
if (value !== undefined) {
obj[key] = value
}
return obj
}, {})
}
function parseObject(arg, accumulation = {}) {
const [name, value] = arg.split('=')
return { ...accumulation, [name]: value }
}
function parseObjectList(arg, accumulation = {}) {
const args = arg.split(',').map((str) => str.trim())
return args.reduce((acc, arg) => parseObject(arg, acc), accumulation)
}
const parseConfig = (name) => (arg) => {
try {
if (arg.endsWith('rc')) {
const content = fs.readFileSync(arg, 'utf-8')
return JSON.parse(content)
}
const ext = path.extname(arg)
if (ext === '.js' || ext === '.json') {
// eslint-disable-next-line import/no-dynamic-require, global-require
return require(path.join(process.cwd(), arg))
}
return JSON.parse(arg)
} catch (error) {
exitError(
`"${name}" is not valid, please specify a valid file or use a inline JSON.`,
)
return null
}
}
program
.version(pkg.version)
.usage('[options] <file|directory>')
.option('--config-file <file>', 'specify the path of the svgr config')
.option(
'--no-runtime-config',
'disable runtime config (".svgrrc", ".svgo.yml", ".prettierrc")',
)
.option('-d, --out-dir <dirname>', 'output files into a directory')
.option('--ignore-existing', 'ignore existing files when used with --out-dir')
.option('--ext <ext>', 'specify a custom file extension (default: "js")')
.option(
'--filename-case <case>',
'specify filename case ("pascal", "kebab", "camel") (default: "pascal")',
)
.option('--icon', 'use "1em" as width and height')
.option('--typescript', 'transform svg into typescript')
.option('--native', 'add react-native support with react-native-svg')
.option('--memo', 'add React.memo into the result component')
.option('--ref', 'forward ref to SVG root element')
.option('--no-dimensions', 'remove width and height from root SVG tag')
.option(
'--expand-props [position]',
'disable props expanding ("start", "end", "none") (default: "end")',
)
.option(
'--svg-props <property=value>',
'add props to the svg element',
parseObjectList,
)
.option(
'--replace-attr-values <old=new>',
'replace an attribute value',
parseObjectList,
)
.option('--template <file>', 'specify a custom template to use')
.option(
'--index-template <file>',
'specify a custom index.js template to use',
)
.option('--no-index', 'disable index file generation')
.option('--title-prop', 'create a title element linked with props')
.option(
'--prettier-config <fileOrJson>',
'Prettier config',
parseConfig('--prettier-config'),
)
.option('--no-prettier', 'disable Prettier')
.option(
'--svgo-config <fileOrJson>',
'SVGO config',
parseConfig('--svgo-config'),
)
.option('--no-svgo', 'disable SVGO')
.option('--silent', 'suppress output')
.option('--stdin', 'force reading input from stdin')
.option(
'--stdin-filepath',
'path to the file to pretend that stdin comes from',
)
program.on('--help', () => {
console.log(`
Examples:
svgr --replace-attr-values "#fff=currentColor" icon.svg
`)
})
program.parse(process.argv)
async function run() {
const errors = []
const filenames = program.args.reduce((globbed, input) => {
let files = glob.sync(input)
if (!files.length) files = [input]
return globbed.concat(files)
}, [])
await Promise.all(
filenames.map(async (filename) => {
try {
await fsPromises.stat(filename)
} catch (error) {
errors.push(`${filename} does not exist`)
}
}),
)
if (errors.length) {
console.error(errors.join('. '))
process.exit(2)
}
const opts = noUndefinedKeys(program.opts())
const config = await loadConfig(opts, { filePath: process.cwd() })
// Back config file
config.configFile = opts.configFile
if (opts.expandProps === 'none') {
config.expandProps = false
}
if (opts.dimensions === true) {
delete config.dimensions
}
if (opts.svgo === true) {
delete config.svgo
}
if (opts.prettier === true) {
delete config.prettier
}
if (opts.template) {
try {
// eslint-disable-next-line global-require, import/no-dynamic-require
const template = require(path.join(process.cwd(), opts.template))
if (template.default) config.template = template.default
else config.template = template
if (typeof config.template !== 'function')
throw new Error('Template must be a function')
} catch (error) {
console.error(`Error when loading template: ${opts.template}\n`)
console.error(error.stack)
process.exit(2)
}
}
if (opts.indexTemplate) {
try {
// eslint-disable-next-line global-require, import/no-dynamic-require
const indexTemplate = require(path.join(
process.cwd(),
opts.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: ${opts.indexTemplate}\n`)
console.error(error.stack)
process.exit(2)
}
}
if (opts.index === false) {
delete config.index
}
const command = opts.outDir ? dirCommand : fileCommand
await command(opts, program, filenames, config)
}
run().catch((error) => {
setTimeout(() => {
throw error
})
})