ura-components/tasks/build-widgets.js

86 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

import fs from 'fs'
import {build} from 'vite'
const PWD = process.cwd()
const clearDir = (path, excludes) => {
var files = []
if (fs.existsSync(path)) {
files = fs.readdirSync(path)
nextFile: for (const file of files) {
2022-10-27 16:58:53 +08:00
if (excludes) {
for (let exclude of excludes) {
if (file === exclude) continue nextFile
}
}
var curPath = path + '/' + file
if (fs.statSync(curPath).isDirectory()) {
clearDir(curPath)
fs.rmdirSync(curPath)
} else {
fs.unlinkSync(curPath)
}
}
}
}
const fun = async (widgetName, entryName) => {
await build({
build: {
lib: {
name: widgetName,
entry: `src/widgets/${widgetName}/${entryName}.ts`,
formats: ['cjs', 'es'],
fileName: `${widgetName}`,
},
outDir: `dist/widgets/${widgetName}/`,
},
})
2022-10-27 16:58:53 +08:00
clearDir(`dist/widgets/${widgetName}`, [
`${widgetName}.cjs`,
`${widgetName}.js`,
])
}
const safeReadDirSync = (path) => {
let dirData = {}
try {
dirData = fs.readdirSync(path)
} catch (ex) {
if (ex.code == 'EACCES' || ex.code == 'EPERM') {
// 无权访问该文件夹,跳过
return null
} else {
throw ex
}
}
return dirData
}
const buildAll = () => {
const widgetsFilePath = `${PWD}/src/widgets`
const dirData = safeReadDirSync(widgetsFilePath)
dirData?.forEach((fileName) => {
const widgetPath = `${widgetsFilePath}/${fileName}`
const stats = fs.statSync(widgetPath)
if (stats.isDirectory()) {
const files = safeReadDirSync(widgetPath)
if (files.includes(`${fileName}.ts`)) {
fun(fileName, fileName)
} else if (files.includes(`index.ts`)) {
fun(fileName, 'index')
} else {
throw new Error(`Entry file of ${fileName} widget dose not exist!`)
}
}
})
}
buildAll()