代码拉取完成,页面将自动刷新
import fs from 'fs'
import path from 'path'
import { defineConfig } from 'vite'
import serveStatic from 'serve-static'
export default defineConfig(async ({ mode }) => {
// const {
// default: { vitePrefabPlugin },
// } = await import('@thing.js/cli-p-prefab')
const { vitePrefabPlugin } = await import('@thing.js/cli-p-prefab')
return {
plugins: [
startLocalServe(),
transformHtml(),
mode === 'development' &&
vitePrefabPlugin({
input: 'src',
outputDir: 'dist',
watch: true,
reloadAfterBuild: true,
reloadFilter: ({ file, type }) => {
return path.basename(file) === 'prefab.json' && type !== 'unlink'
},
}),
],
}
})
/**
* Start packaging prefab
*/
function startLocalServe() {
return {
name: 'local-serve',
async configureServer(server) {
const app = server.middlewares
app.use(serveStatic('dist'))
app.use('/local-api/export-data', (req, res) => {
const data = []
req.on('data', (chunk) => {
data.push(chunk)
})
req.on('end', () => {
try {
let newObj = JSON.parse(Buffer.concat(data).toString())
let result = {}
const tsfPath = path.resolve(__dirname, 'src/prefab.json')
if (fs.existsSync(tsfPath)) {
try {
const oldObj = JSON.parse(fs.readFileSync(tsfPath, 'utf8'))
const headers = [
'name',
'id',
'version',
'author',
'description',
]
// Place the old header in front
for (const key in oldObj) {
if (
headers.includes(key) &&
typeof oldObj[key] !== 'undefined'
) {
result[key] = oldObj[key]
}
}
} catch (e) {
console.error(e)
}
}
for (const key in newObj) {
result[key] = newObj[key]
}
fs.writeFileSync(tsfPath, JSON.stringify(result, null, 2))
res.end()
} catch (e) {
console.log(e)
}
})
})
},
}
}
/**
* Inject export script to index.html
*/
function transformHtml() {
return {
name: 'transform-html',
transformIndexHtml() {
return [
{
tag: 'script',
attrs: {
type: 'module',
},
children: `
import exportData from "./dist/index.js";
fetch('/local-api/export-data', {method: 'POST', body: JSON.stringify(exportData(), null, 2)})
`,
injectTo: 'body',
},
]
},
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。