vite.config.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. const fs = require("fs");
  2. const path = require("path");
  3. const { defineConfig } = require("vite");
  4. const { viteSingleFile } = require("vite-plugin-singlefile");
  5. const platformBuilds = {
  6. applovin: { adapter: "applovin", output: "applovin" },
  7. unity: { adapter: "unity", output: "unity" },
  8. playturbo: { adapter: "playturbo", output: "playturbo" },
  9. mintegral: { adapter: "playturbo", output: "mintegral" },
  10. google: { adapter: "google", output: "google" },
  11. };
  12. function patchSingleFileHtml(htmlPath) {
  13. if (!fs.existsSync(htmlPath)) return;
  14. const html = fs
  15. .readFileSync(htmlPath, "utf8")
  16. .replace(/<script\s+type="module"\s+crossorigin>/g, "<script>")
  17. .replace(/<script\s+crossorigin\s+type="module">/g, "<script>")
  18. .replace(/<script\s+type="module">/g, "<script>")
  19. .replace(/<script\s+crossorigin>/g, "<script>")
  20. .replace(/<style\s+rel="stylesheet"\s+crossorigin>/g, "<style>")
  21. .replace(/<style\s+crossorigin\s+rel="stylesheet">/g, "<style>")
  22. .replace(/<style\s+crossorigin>/g, "<style>");
  23. fs.writeFileSync(htmlPath, html);
  24. }
  25. function finalizeHtmlPlugin(outDir, fileName) {
  26. return {
  27. name: "finalize-html-output",
  28. closeBundle() {
  29. const indexPath = path.resolve(__dirname, outDir, "index.html");
  30. const targetPath = path.resolve(__dirname, outDir, fileName);
  31. if (fileName !== "index.html" && fs.existsSync(indexPath)) {
  32. fs.renameSync(indexPath, targetPath);
  33. }
  34. patchSingleFileHtml(targetPath);
  35. },
  36. };
  37. }
  38. module.exports = defineConfig(({ mode }) => {
  39. const platformBuild = platformBuilds[mode];
  40. const adapter = platformBuild?.adapter || "google";
  41. const output = platformBuild?.output;
  42. const outDir = output ? `dist/${output}` : "dist";
  43. const htmlFileName = output ? `${output}.html` : "index.html";
  44. return {
  45. plugins: [viteSingleFile(), finalizeHtmlPlugin(outDir, htmlFileName)],
  46. resolve: {
  47. alias: {
  48. "./ad-platform/current": path.resolve(
  49. __dirname,
  50. `src/filler/ad-platform/adapters/${adapter}.ts`,
  51. ),
  52. },
  53. },
  54. build: {
  55. // 所有资源内联到 HTML,目标单文件广告
  56. assetsInlineLimit: 100 * 1024 * 1024, // 不限大小,全部内联
  57. target: "es2017",
  58. outDir,
  59. emptyOutDir: true,
  60. rollupOptions: {
  61. input: {
  62. [path.basename(htmlFileName, ".html")]: "./index.html",
  63. },
  64. output: {
  65. entryFileNames: "assets/[name].js",
  66. chunkFileNames: "assets/[name].js",
  67. assetFileNames: (assetInfo) => {
  68. if (assetInfo.name && assetInfo.name.endsWith(".html")) {
  69. return htmlFileName;
  70. }
  71. return "assets/[name][extname]";
  72. },
  73. },
  74. },
  75. },
  76. };
  77. });