Skip to content

Instantly share code, notes, and snippets.

@vdanchenkov
Created Jun 20, 2022
Embed
What would you like to do?
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

vdanchenkov commented Jun 20, 2022

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