🐟

AstroでbuildしたHTMLファイル内の絶対パスを相対パスに置換する

2023.05.12

SHARE

TABLE OF CONTENTS

    🐟

    AstroでbuildしたHTMLファイル内の絶対パスを相対パスに置換する

    2023.05.12

    絶対パスを相対パスに置換する際にastro-relative-linksを使用していましたが、自分好みに「astro.config.mjs」の内容を組んだ際に正しく実行されなかったため「node」で実行することにしました。

    コード

    import { writeFileSync, readFileSync } from "fs";
    import glob from "glob";
    
    const replaceInHtmlFiles = () => {
      try {
        const files = glob.sync("dist/**/*.html");
    
        for (const file of files) {
          // htmlファイルの読み込み
          const data = readFileSync(file, "utf8");
    
          // htmlの置かれているパスから相対(., ..)を算出
          let relativePath = file.replace(/[^/]/g, "").replace(/\//g, ".");
    
          if (relativePath.length === 1) {
            relativePath = file.replace(/[^/]/g, "").replace(/\//g, ".");
          } else {
            relativePath = file.replace(/[^/]/g, "").replace(/\//g, "../");
            if (file.includes("index.html")) {
              relativePath = relativePath.slice(0, -4);
              // 3 ... | ../../ → ..
              // 4 .... | ../../../ → ../..
              // 5 ..... | ../../../../ → ../../..
            } else {
              relativePath = relativePath.slice(0, -1);
              // 3 ... | ../../ → ../..
              // 4 .... | ../../../ → ../../..
              // 5 ..... | ../../../../ → ../../../..
            }
          }
    
          // 絶対パスを相対パスに置換する
          const result = data
            .replace(/href="\//g, `href="${relativePath}/`)
            .replace(/href='\//g, `href='${relativePath}/`)
            .replace(/src="\//g, `src="${relativePath}/`)
            .replace(/src='\//g, `src='${relativePath}/`)
            .replace(/srcset="\//g, `srcset="${relativePath}/`)
            .replace(/srcset='\//g, `srcset='${relativePath}/`)
            .replace(/action="\//g, `action="${relativePath}/`)
            .replace(/action='\//g, `action='${relativePath}/`)
            .replace(/content="\//g, `content="${relativePath}/`)
            .replace(/content='\//g, `content='${relativePath}/`);
    
          writeFileSync(file, result, "utf8");
        }
      } catch (error) {
        console.log(error);
      }
    };
    
    replaceInHtmlFiles();

    □ 置換対応している属性内容

    • href
    • src
    • srcset
    • action
    • content

    実行方法

    「build」後に手動で行う場合

    node replaceHtml.mjs

    「build」時に直列で実行する場合

    {
      "scripts": {
        "build": "astro build && node replaceHtml.mjs",
      },
    }
    npm run build

    参考サイト

    ©2025 SHOYA KAJITA.