Skip to content

Instantly share code, notes, and snippets.

@Pezmc
Last active April 3, 2023 14:52
Show Gist options
  • Save Pezmc/9d78ce0a6fea39e80b501e8c48b24586 to your computer and use it in GitHub Desktop.
Save Pezmc/9d78ce0a6fea39e80b501e8c48b24586 to your computer and use it in GitHub Desktop.
Re-write webpack alias into relative imports
const fs = require('fs')
const { cwd } = require('node:process')
const path = require('path')
const readline = require('readline')
const {
glob
} = require('glob')
/**
* Should be run from the directory that files should be resolved to
* i.e. from wherever the alias currently points
* @param {string} alias An alias to replace with a relative path to the CWD
*/
async function main (alias) {
const jsfiles = await glob('**/*.{js,vue}')
const regExp = new RegExp(`from '${alias}/(.*)'`) // assumed single quotes
for (const file of jsfiles) {
const readFile = readline.createInterface({
input: fs.createReadStream(file),
output: fs.createWriteStream(`${file}.new`),
terminal: false
})
const dirname = path.dirname(file)
readFile
.on('line', transform)
.on('close', function () {
fs.rename(`${file}.new`, `${file}`, (err) => {
if (err) throw err
console.info(`Updated ${file} successfully!`)
})
})
function transform (line) {
const matches = line.match(regExp)
if (matches) {
let relative = path.relative(dirname, path.join(cwd(), matches[1])) || './'
if (!relative.includes('../')) {
relative = `./${relative}`
}
const newLine = line.replace(regExp, `from '${relative}'`)
this.output.write(`${newLine}\n`)
} else {
this.output.write(`${line}\n`)
}
}
}
}
main('@core')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment