// 如果运行报错 Cannot use import statement outside a module 换成
// const fs = require("fs");
import fs from "fs";

const htmlPath = "./dist/index.html"; // 打包后的html文件路径
const htmlText = fs.readFileSync(htmlPath, 'utf8');
const htmlArr = htmlText.match(/.*\n/g) || [];

let result = "";
let count = 1;

htmlArr.forEach(v => {
  v = v
    .replace(/script ?nomodule\s?/g, "script ")
    .replace(/\s?crossorigin\s?/g, " ")
    .replace(/data-src/g, 'src');
  if (!v.includes(`script type="module"`)) {
    result += v;
  }
});


let result_arr = result.match(/.*\n/g) || [];
result = ""
result_arr.forEach(v => {
  // 处理内联脚本
  if (v.includes(`script`)) {
    let start_index = v.indexOf('>');
    let end_index = v.lastIndexOf('<')
    let script_str = v.substring(start_index + 1, end_index)
    if (count === 1) {
      let path = "./dist/assets/" + String(count) + ".js";
      fs.writeFileSync(path, script_str, 'utf8');
      path = "." + path.substring(6)
      v = v.substring(0, start_index) + " src=\"" + path + "\">" + v.substring(end_index);
    }
    else if (count === 3) {
      let path = "./dist/assets/" + String(count) + ".js";
      v = v.substring(0, start_index + 1) + v.substring(end_index);
      fs.writeFileSync(path, script_str, 'utf8');
      path = "." + path.substring(6)
      v += "\n  <script  type=\"application/javascript\" src=\"" + path + "\"></script>";
    }
    count++;
    v = v.substring(0, 12) + " type=\"application/javascript\" " + v.substring(12);
    // console.log(v);
  }
  if (!v.includes(`script type="module"`)) {
    result += v;
  }
})


fs.writeFileSync(htmlPath, result, 'utf8');

console.log("处理完成");