49 lines
1.5 KiB
TypeScript
49 lines
1.5 KiB
TypeScript
import fs from "node:fs";
|
||
import path from "node:path";
|
||
import vue from "@vitejs/plugin-vue";
|
||
import { defineConfig, type Plugin } from "vite";
|
||
|
||
const repoWasmDir = path.resolve(__dirname, "../public/wasm");
|
||
|
||
// 复用主项目已经构建好的 WASM 文件,开发时映射 /wasm,打包时复制到 dist/wasm。
|
||
function repoWasmAssets(): Plugin {
|
||
return {
|
||
name: "repo-wasm-assets",
|
||
configureServer(server) {
|
||
server.middlewares.use("/wasm", (req, res, next) => {
|
||
const requestPath = decodeURIComponent((req.url || "").split("?")[0].replace(/^\/+/, ""));
|
||
const filePath = path.resolve(repoWasmDir, requestPath);
|
||
if (!filePath.startsWith(repoWasmDir) || !fs.existsSync(filePath)) {
|
||
next();
|
||
return;
|
||
}
|
||
|
||
if (filePath.endsWith(".wasm")) {
|
||
res.setHeader("Content-Type", "application/wasm");
|
||
} else if (filePath.endsWith(".js")) {
|
||
res.setHeader("Content-Type", "application/javascript; charset=utf-8");
|
||
}
|
||
|
||
fs.createReadStream(filePath).pipe(res);
|
||
});
|
||
},
|
||
closeBundle() {
|
||
const outDir = path.resolve(__dirname, "dist/wasm");
|
||
fs.mkdirSync(outDir, { recursive: true });
|
||
for (const assetName of ["smart_math.js", "smart_math.wasm"]) {
|
||
const source = path.join(repoWasmDir, assetName);
|
||
if (fs.existsSync(source)) {
|
||
fs.copyFileSync(source, path.join(outDir, assetName));
|
||
}
|
||
}
|
||
}
|
||
};
|
||
}
|
||
|
||
export default defineConfig({
|
||
plugins: [vue(), repoWasmAssets()],
|
||
server: {
|
||
port: 5174
|
||
}
|
||
});
|