Last active
April 23, 2022 17:22
-
-
Save jgdev/408690d6b5d7352e6fa1fd569773d683 to your computer and use it in GitHub Desktop.
TypeScript resolve root path alias script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from 'fs' | |
import path from 'path' | |
function listJsFiles(dir) { | |
return fs.readdirSync(path.resolve('.', dir)).reduce((files, file) => { | |
let result = [...files] | |
const filePath = path.join(dir, file) | |
if (fs.lstatSync(filePath).isDirectory()) { | |
result = result.concat(listJsFiles(filePath)) | |
} | |
if (filePath.endsWith('.js')) { | |
result = result.concat(filePath) | |
} | |
return result | |
}, []) | |
} | |
function replaceModuleAlias(file, dir) { | |
const relativeModule = path.relative(path.join(file, '..'), path.join(process.cwd(), dir)) | |
const fileData = fs.readFileSync(file).toString('utf-8') | |
const replacingMatch = fileData.match(/require\("@\/(.*)"\)/gim) | |
if (!replacingMatch) return null | |
const toReplace = replacingMatch.map((toReplace) => | |
toReplace.replace('@/', (relativeModule && relativeModule + path.sep) || './') | |
) | |
return toReplace.reduce( | |
(result, _, index) => result.replace(replacingMatch[index], toReplace[index]), | |
fileData | |
) | |
} | |
const distributionDirectory = './dist' | |
let filesChanged = 0 | |
listJsFiles(distributionDirectory).forEach((file) => { | |
const replaceData = replaceModuleAlias(file, distributionDirectory) | |
if (replaceData) { | |
fs.writeFileSync(file, replaceData, { encoding: 'utf-8' }) | |
filesChanged++ | |
} | |
}) | |
console.log(`Changed ${filesChanged} files with module aliases`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment