import { defineConfig } from "vite";
import { resolve } from "path";
import { splitVendorChunkPlugin } from "vite";
import glslify from "rollup-plugin-glslify";
import dynamicImport from "vite-plugin-dynamic-import";
const root = "src";

export default defineConfig({
  root,
  base: "/",
  publicDir: "../public",
  plugins: [
    dynamicImport(),
    splitVendorChunkPlugin(),
    glslify({
      compress(code) {
        // Based on https://github.com/vwochnik/rollup-plugin-glsl
        // Modified to remove multiline comments. See #16
        let needNewline = false;
        return code
          .replace(
            /\\(?:\r\n|\n\r|\n|\r)|\/\*.*?\*\/|\/\/(?:\\(?:\r\n|\n\r|\n|\r)|[^\n\r])*/gs,
            ""
          )
          .split(/\n+/)
          .reduce((result, line) => {
            line = line.trim().replace(/\s{2,}|\t/, " "); // lgtm[js/incomplete-sanitization]
            if (line.charAt(0) === "#" || /else/.test(line)) {
              if (needNewline) {
                result.push("\n");
              }
              result.push(line, "\n");
              needNewline = false;
            } else {
              result.push(
                line.replace(
                  /\s*({|}|=|\*|,|\+|\/|>|<|&|\||\[|\]|\(|\)|-|!|;)\s*/g,
                  "$1"
                )
              );
              needNewline = true;
            }
            return result;
          }, [])
          .join(process.env.NODE_ENV === "development" ? "\n" : "")
          .replace(/\n+/g, "\n");
      },
    }),
  ],
  resolve: {
    alias: {
      "#": resolve(__dirname, root, `scripts`),
      three: resolve(__dirname, "node_modules", "three"),
    },
  },
  build: {
    outDir: "../dist",
    rollupOptions: {
      input: {
        // htmlを追加する場合にはこちらに追記
        // If you want to add HTML files, add them here
        index: resolve(root, "index.html"),
        baron: resolve(root, "baron.html"),
        chihiro: resolve(root, "chihiro.html"),
        howl: resolve(root, "howl.html"),
        laputa: resolve(root, "laputa.html"),
        majo: resolve(root, "majo.html"),
        mononoke: resolve(root, "mononoke.html"),
        nausicaa: resolve(root, "nausicaa.html"),
        ponyo: resolve(root, "ponyo.html"),
        porco: resolve(root, "porco.html"),
        totoro: resolve(root, "totoro.html"),
      },
    },
  },
  server: {
    host: true,
  },
});
