vite.config.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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, adapter) {
  13. if (!fs.existsSync(htmlPath)) return;
  14. let 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. // Google 平台需要引入 exitapi.js,CTA 才能正常跳转
  24. if (adapter === "google") {
  25. html = html.replace(
  26. "</head>",
  27. '<script src="https://tpc.googlesyndication.com/pagead/js/exitapi.js"></script></head>',
  28. );
  29. }
  30. fs.writeFileSync(htmlPath, html);
  31. }
  32. function finalizeHtmlPlugin(outDir, adapter) {
  33. return {
  34. name: "finalize-html-output",
  35. closeBundle() {
  36. const htmlPath = path.resolve(__dirname, outDir, "index.html");
  37. patchSingleFileHtml(htmlPath, adapter);
  38. },
  39. };
  40. }
  41. module.exports = defineConfig(({ mode }) => {
  42. const platformBuild = platformBuilds[mode];
  43. const adapter = platformBuild?.adapter || "google";
  44. const output = platformBuild?.output;
  45. const outDir = output ? `dist/${output}` : "dist";
  46. return {
  47. plugins: [viteSingleFile(), finalizeHtmlPlugin(outDir, adapter)],
  48. resolve: {
  49. alias: {
  50. "./ad-platform/current": path.resolve(
  51. __dirname,
  52. `src/filler/ad-platform/adapters/${adapter}.ts`,
  53. ),
  54. },
  55. },
  56. build: {
  57. // 所有资源内联到 HTML,目标单文件广告
  58. assetsInlineLimit: 100 * 1024 * 1024, // 不限大小,全部内联
  59. target: "es2017",
  60. outDir,
  61. emptyOutDir: true,
  62. rollupOptions: {
  63. input: {
  64. main: "./index.html",
  65. },
  66. output: {
  67. entryFileNames: "assets/[name].js",
  68. chunkFileNames: "assets/[name].js",
  69. assetFileNames: "assets/[name][extname]",
  70. },
  71. },
  72. },
  73. };
  74. });