import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createHtmlPlugin } from 'vite-plugin-html';
import { resolve } from 'path'
import vueSetupExtend from 'unplugin-vue-setup-extend-plus/vite'
import path from 'path';
import fs from 'fs';
try {
  const vue_bundler_file = path.resolve(
    __dirname,
    "node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js"
  );
  //使用同步读取文件
  let data = fs.readFileSync(vue_bundler_file, "utf8");
  //如果未添加过
  if (data.indexOf("//__v_cache") < 0) {
    console.log("正在修改源码文件：", vue_bundler_file);
    //先找到__v_cache变量的位置
    let index = data.indexOf("__v_cache");
    if (index >= 0) {
      // 继续往前找if关键字
      index = data.lastIndexOf("if ", index);
      if (index >= 0) {
        //从上一个位置开始
        index -= 1;
        //然后放一个注释
        const comment = " //__v_cache ";
        //然后拼接
        data = data.substring(0, index) + comment + data.substring(index);

        //继续往后找下一个大括号 }
        index = data.indexOf("}", index);
        if (index >= 0) {
          //从上一个位置开始
          index -= 1;
          //然后拼接
          data = data.substring(0, index) + comment + data.substring(index);
        }

        fs.writeFileSync(vue_bundler_file, data, "utf8");
      }
    }
  }
} catch (er) {
  console.error(er.message);
}

// https://vitejs.dev/config/
export default defineConfig({
  base: "./",
  plugins: [
    vue(),
    createHtmlPlugin({
      minify: true
    }),
    vueSetupExtend({
      
    })
  ],
  server: {
    host: '0.0.0.0',	//解决“vite use `--host` to expose”
    port: 8080,
    open: true,
    hmr: true
  },
  resolve: {
    preserveSymlinks: true,
    alias: [
      {
        find: '@',
        replacement: resolve(__dirname, 'src')
      }
    ]
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: '@import "./src/style.scss";', //导入全局样式
        javascriptEnabled: true
      }
    }
  },
  build: {
    minify: "terser",
    terserOptions: {
      compress: {
        //生产环境时移除console
        drop_console: true
      }
    }
  },
  esbuild: {
    jsxFactory: 'h',
    jsxFragment: 'Fragment',
    jsxInject: "import { h } from 'vue';"
  }
})
