Created
April 23, 2021 09:04
-
-
Save davidhellmann/c5dc336006236e71185fe44134aaceea to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require('path'); | |
const fs = require('fs'); | |
const glob = require('glob'); | |
const srcDir = path.resolve(path.join(process.cwd(), 'src', 'components/_svg')); | |
const distDir = path.resolve(path.join(process.cwd(), 'src', 'components/_svg')); | |
function readSVG(file) { | |
return fs.readFileSync(file, 'utf-8'); | |
} | |
function convertToVue(content, name, size) { | |
const contentToWrite = ` | |
<template> | |
<div :class="rootClass" | |
:style="\` | |
width: \${width}; | |
height: \${height}; | |
\`"> | |
${content} | |
</div> | |
</template> | |
<script> | |
export default { | |
name: '${name}', | |
props: { | |
color: { | |
type: String, | |
default: 'white', | |
}, | |
width: { | |
type: String, | |
default: '${size[0]}px', | |
}, | |
height: { | |
type: String, | |
default: '${size[1]}px', | |
}, | |
}, | |
data() { | |
return { | |
cn: 'svg-${name}', | |
}; | |
}, | |
computed: { | |
rootClass() { | |
return \`\${this.cn} \${this.cn}--\${this.color}\`; | |
}, | |
}, | |
}; | |
</script> | |
<style lang="scss"> | |
.svg-${name} { | |
svg { | |
width: 100%; | |
height: 100%; | |
} | |
path { | |
fill: c('white'); | |
transition: all 0.25s ease; | |
} | |
} | |
.svg-${name}--black { | |
path { | |
fill: c('black'); | |
} | |
} | |
.svg-${name}--red { | |
path { | |
fill: c('red'); | |
} | |
} | |
.svg-${name}--gray { | |
path { | |
fill: c('white', '30%'); | |
} | |
} | |
.svg-${name}--blue { | |
path { | |
fill: c('blue'); | |
} | |
} | |
</style> | |
`; | |
return contentToWrite; | |
}; | |
function writeFile(content, name) { | |
fs.writeFileSync(`${distDir}/${name}.vue`, content); | |
console.log(`File created: ${name}`); | |
} | |
function readAndWrite() { | |
const svgFiles = glob.sync(srcDir + '**/**/*.svg'); | |
svgFiles.forEach(file => { | |
const filePath = path.dirname(file); | |
const iconDir = filePath.split(srcDir)[1]; | |
const fileContent = readSVG(file); | |
const size = fileContent.match(/viewbox=['"]([\d \.]+)['"]/i)[1] | |
.split(/\s/).slice(-2).map(parseFloat); | |
const componentName = path.basename(file, '.svg'); | |
const vueContent = convertToVue(fileContent, componentName, size); | |
writeFile(vueContent, `${iconDir}/${componentName}`); | |
}); | |
} | |
readAndWrite(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment