aboutsummaryrefslogtreecommitdiff
path: root/scripts/build-react.js
blob: 2aa87d0e9f59c7743d9ab288c8c16f5e05163284 (plain)
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
#!/usr/bin/env node

import glob from 'glob'
import path from 'path'
import fs from 'fs'
import svgr from '@svgr/core'
import { asyncForEach, camelize, optimizeSvgCode } from './utils'

const packageDir = path.resolve(__dirname, '../packages/icons-react')

const componentTemplate = function template(
    { template },
    opts,
    { imports, componentName, props, jsx, exports },
) {
  return template.ast`
    ${imports}
    function ${componentName}({ size = 24, color = "currentColor", stroke = 2, ...props }) { return (${jsx}); }
    ${exports}
  `;
}

const componentName = function (file) {
  file = path.basename(file, '.svg')
  file = camelize(`Icon ${file}`)

  return file
}

const buildReact = async () => {
  let files = glob.sync(`./dist/icons/*.svg`)

  let indexCode = '',
      indexDCode = `import { FC, SVGAttributes } from 'react';

interface TablerIconProps extends SVGAttributes<SVGElement> { color?: string; size?: string | number; stroke?: string | number; }

type TablerIcon = FC<TablerIconProps>;\n\n`

  await asyncForEach(files, async function (file) {
    const svgCode = optimizeSvgCode(fs.readFileSync(file).toString()),
        fileName = path.basename(file, '.svg') + '.js',
        iconComponentName = componentName(file)

    fs.mkdirSync(`${packageDir}/icons/`, { recursive: true })

    await svgr(svgCode, {
      icon: false,
      svgProps: { width: '{size}', height: '{size}', strokeWidth: '{stroke}', stroke: '{color}' },
      template: componentTemplate
    }, { componentName: iconComponentName }).then(jsCode => {
      fs.writeFileSync(`${packageDir}/icons/${fileName}`, jsCode)

      indexCode += `export { default as ${iconComponentName} } from './icons/${fileName}';\n`
      indexDCode += `export const ${iconComponentName}: TablerIcon;\n`
    })

    fs.writeFileSync(`${packageDir}/index.js`, indexCode)
    fs.writeFileSync(`${packageDir}/index.d.ts`, indexDCode)
  })
}


buildReact()