Skip to content

Instantly share code, notes, and snippets.

@vdanchenkov
Created June 20, 2022 07:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vdanchenkov/6fe439c1e35545572d8f64c8aea66595 to your computer and use it in GitHub Desktop.
Save vdanchenkov/6fe439c1e35545572d8f64c8aea66595 to your computer and use it in GitHub Desktop.
Generate ReScript module for icons
const chokidar = require('chokidar')
const fs = require('fs')
let emitComponent = (name, path) => {
return `module ${name} = {
@module("../svg/${path}") @react.component
external make: (
~width: int=?,
~height: int=?,
~className: string=?
) => React.element = "default"
}
`
}
const rebuild = (watched) => {
let components = []
Object.entries(watched).forEach(([key, files]) => {
let namePrefix = key == '.' ? '' : `${key}__`
let pathPrefix = key == '.' ? '' : `${key}/`
files.forEach((fileName) => {
if (fileName.includes('.svg')) {
let [name] = fileName.split('.')
components.push(emitComponent(namePrefix + name, pathPrefix + fileName))
}
})
})
fs.writeFileSync('./components/Icon.res', components.sort().join('\n'))
}
const watcher = chokidar.watch('.', { ignoreInitial: true, cwd: './svg' })
watcher
.on('add', () => rebuild(watcher.getWatched()))
.on('unlink', () => rebuild(watcher.getWatched()))
.on('ready', () => rebuild(watcher.getWatched()))
@vdanchenkov
Copy link
Author

watches ./svg/**

Given there are an image with path ./svg/Foo/Bar.svg, following content will be generated in ./components/Icon.res

module Foo__Bar = {
  @module("../svg/Foo/Bar.svg") @react.component
  external make: (
    ~width: int=?,
    ~height: int=?,
    ~className: string=?
  ) => React.element = "default"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment