Răsfoiți Sursa

fix: add hack for gastby add hash to different file

代强 2 ani în urmă
părinte
comite
6abe1ffd69
1 a modificat fișierele cu 30 adăugiri și 0 ștergeri
  1. 30 0
      gatsby-node.js

+ 30 - 0
gatsby-node.js

@@ -349,4 +349,34 @@ exports.onPostBuild = async () => {
         }
     }
 
+    const jsFiles = glob.sync(`${publicPath}/*.js`);
+
+    const replaceNames = {};
+    for (let file of jsFiles) {
+        const filename = path.basename(file);
+        const fileNameWithoutExt = filename.split('.')[0];
+        const originHash = fileNameWithoutExt.split('-').at(-1);
+
+        if (originHash && originHash!==fileNameWithoutExt){
+            let fileNameWithoutExtWithHash = fileNameWithoutExt.replace(originHash, `${originHash}${numHash}`);
+            replaceNames[originHash] = `${originHash}${numHash}`;
+            fs.renameSync(file, path.join(path.dirname(file), `${fileNameWithoutExtWithHash}.js`));
+        } else {
+            let finalFileName = `${fileNameWithoutExt}${numHash}.js`;
+            replaceNames[filename] = finalFileName;
+            fs.renameSync(file, path.join(path.dirname(file), finalFileName));
+        }
+    }
+    const allFiles = glob.sync(`${publicPath}/**/*.{js,html,json}`);
+    for (let file of allFiles) {
+        const stats = fs.statSync(file);
+        if (stats.isFile()) {
+            let result = fs.readFileSync(file, 'utf8');
+            for (let [oldName, newName] of Object.entries(replaceNames)) {
+                result = result.replaceAll(oldName, newName);
+            }
+            fs.writeFileSync(file, result, 'utf8');
+        }
+    }
+
 };