|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const fs = require('fs-extra') |
| 4 | +const path = require('path') |
| 5 | +const recursiveReaddir = require('recursive-readdir') |
| 6 | + |
| 7 | +const buildDirectory = path.join(__dirname, 'build') |
| 8 | +const absoluteUrlRegExp = /(href|src)="(?!http[s]|ftp?:\/\/)([^"|#]+)"/g |
| 9 | + |
| 10 | +const isDirectory = (dirPath) => path.extname(dirPath) === '' |
| 11 | + |
| 12 | +const convertAbsolutePathsToRelative = (content, filePath) => |
| 13 | + content.replace(absoluteUrlRegExp, (_absoluteUrl, $1, $2) => { |
| 14 | + const currentDirPath = path.dirname(filePath) |
| 15 | + const relativeDirPath = |
| 16 | + currentDirPath === '.' ? '.' : path.relative(currentDirPath, '') |
| 17 | + |
| 18 | + let relativePath = path.join(relativeDirPath, $2) |
| 19 | + if (isDirectory(relativePath)) { |
| 20 | + relativePath = path.join(relativePath, 'index.html') |
| 21 | + } |
| 22 | + |
| 23 | + return `${$1}="${relativePath}"` |
| 24 | + }) |
| 25 | + |
| 26 | +const websiteTextualFileExtensions = ['.css', '.js', '.html', '.xml'] |
| 27 | +const isNotWebsiteTextualFile = (filePath, stats) => |
| 28 | + !( |
| 29 | + stats.isDirectory() || |
| 30 | + websiteTextualFileExtensions.includes(path.extname(filePath)) |
| 31 | + ) |
| 32 | + |
| 33 | +const postProcess = async () => { |
| 34 | + const filePaths = await recursiveReaddir(buildDirectory, [ |
| 35 | + isNotWebsiteTextualFile |
| 36 | + ]) |
| 37 | + await Promise.all( |
| 38 | + filePaths.map(async (filePath) => { |
| 39 | + const content = await fs.readFile(filePath) |
| 40 | + const relativePath = path.relative(buildDirectory, filePath) |
| 41 | + await fs.writeFile( |
| 42 | + filePath, |
| 43 | + convertAbsolutePathsToRelative(String(content), relativePath) |
| 44 | + ) |
| 45 | + }) |
| 46 | + ) |
| 47 | +} |
| 48 | + |
| 49 | +postProcess() |
0 commit comments