簡體   English   中英

如何使用數百個腳本縮小 index.html 文件?

[英]How to minify index.html file with hundreds of scripts?

我剛剛加入了一個使用 vanilla JS 的現有項目,我正在嘗試縮小我們的源代碼。 不幸的是,index.js 中沒有對 javascript 文件的引用(由於在 index.html 文件中聲明了外部腳本,所有變量都是全局的。),因此 WebPack 等解決方案不起作用。

是否有解決方案可以解析 index.html 中的所有外部腳本標記以將其縮小為單個單獨的 js 文件?

如果它是一個單頁應用程序,每個腳本都在 HTML 文件中同步鏈接(沒有模塊之類的東西),它應該非常簡單

在 html 文件的末尾添加此內容將幫助您以良好的執行順序檢索內容:

(async () => {

  // get the scripts contents
  var scripts = await Promise.all(
    Array.from( document.querySelectorAll("script") )
    .map( x => x.src )
    .map( x => fetch(x).then( x => x.text()))
  )

  // package them into one Blob
  var blob = new Blob(
    [scripts.join("\n\n")], 
    {type: "text/plain"}
  );

  // send it to a server script
  let xhr = new XMLHttpRequest();
  xhr.open("POST", "upload.php", true);
  xhr.onload = () => console.log("sent");
  xhr.send(blob);

})();

然后您可以使用您選擇的任何工具縮小/丑化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM