sakura/scripts/import-svg-icons.mjs
2021-07-20 11:57:41 +08:00

54 lines
1.4 KiB
JavaScript

import { readdirSync, writeFileSync } from 'fs'
import camelCase from 'camelcase'
const iconDir = './src/assets/icons/ui'
const targetDir = './src/components/icon/UiIcon.vue'
const template = (importContent, dataContent) => `
<!-- # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -->
<!-- # Generated by scripts/import-svg-icons.js -->
<template>
<svg-icon :data="svg[$props.name]" original></svg-icon>
</template>
<script>
import { defineComponent } from 'vue'
${importContent}
export default defineComponent({
name: 'Icon',
props: {
name: { type: String },
},
setup(){
const svg = {
${dataContent}
}
return {
svg
}
}
})
</script>
`
const importTemplate = (name, camelCaseName) =>
`import ${camelCaseName} from '@/assets/icons/ui/${name}.svg';\n`
const dataTemplate = (name, camelCaseName) => `'${name}':${camelCaseName},\n`
let importContent = '',
dataContent = ''
readdirSync(iconDir).forEach((file) => {
if (/(.*)\.svg$/.test(file)) {
// console.log(file)
const name = file.match(/(.*)\.svg$/)[1]
const camelCaseName = camelCase(name)
importContent += importTemplate(name, camelCaseName)
dataContent += dataTemplate(name, camelCaseName)
} else {
return false
}
})
const vueContent = template(importContent, dataContent)
writeFileSync(targetDir, vueContent, { flag: 'w+' })