devPlugin.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { ViteDevServer } from "vite";
  2. import path from "path";
  3. export let devPlugin = () => {
  4. return {
  5. name: "dev-plugin",
  6. configureServer(server: ViteDevServer) {
  7. require("esbuild").buildSync({
  8. entryPoints: ["./src/main/mainEntry.ts"],
  9. bundle: true,
  10. platform: "node",
  11. outfile: "./dist/mainEntry.js",
  12. external: ["electron", "pg", "tedious", "mysql", "mysql2", "oracledb", "pg-query-stream", "sqlite3"],
  13. });
  14. // require("esbuild").buildSync({
  15. // entryPoints: ["./src/main/preload.ts"],
  16. // bundle: true,
  17. // platform: "node",
  18. // outfile: "./dist/preload.js",
  19. // external: ["electron", "pg", "tedious", "mysql", "mysql2", "oracledb", "pg-query-stream", "sqlite3"],
  20. // });
  21. if (!server.httpServer) throw new Error("server.httpServer is null check devPlugin.ts ");
  22. // 转移logo文件至dist目录
  23. let targetPath = path.resolve(__dirname, "../dist/logo.ico");
  24. let logoPath = path.resolve(__dirname, "../static/logo.ico");
  25. require("fs").copyFileSync(logoPath, targetPath);
  26. server.httpServer?.once("listening", () => {
  27. let { spawn } = require("child_process");
  28. let addressInfo = server.httpServer?.address() as any;
  29. // console.log(server);
  30. // console.log(addressInfo);
  31. if (addressInfo.address == "0.0.0.0"){
  32. addressInfo.address = "127.0.0.1"
  33. }
  34. let httpAddress = `http://${addressInfo.address}:${addressInfo.port}`;
  35. let electronProcess = spawn(require("electron").toString(), ["./dist/mainEntry.js", httpAddress], {
  36. cwd: process.cwd(),
  37. stdio: "inherit",
  38. });
  39. electronProcess.on("close", () => {
  40. server.close();
  41. process.exit();
  42. });
  43. });
  44. },
  45. };
  46. };
  47. type ResultObject = {
  48. [key: string]: () => { find: RegExp; code: string };
  49. };
  50. export let getReplacer = () => {
  51. let externalModels = ["os", "fs", "path", "events", "child_process", "crypto", "http", "buffer", "url", "better-sqlite3", "knex"];
  52. let result:ResultObject = {};
  53. for (let item of externalModels) {
  54. result[item] = () => ({
  55. find: new RegExp(`^${item}$`),
  56. code: `const ${item} = require('${item}');export { ${item} as default }`,
  57. });
  58. }
  59. result["electron"] = () => {
  60. let electronModules = ["clipboard", "ipcRenderer", "nativeImage", "shell", "webFrame"].join(",");
  61. return {
  62. find: new RegExp(`^electron$`),
  63. code: `const {${electronModules}} = require('electron');export {${electronModules}}`,
  64. };
  65. };
  66. return result;
  67. };