Skip to content

Instantly share code, notes, and snippets.

@swashcap
Created July 31, 2019 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swashcap/49a6b94a44dbdf34c837e3fbe9d64466 to your computer and use it in GitHub Desktop.
Save swashcap/49a6b94a44dbdf34c837e3fbe9d64466 to your computer and use it in GitHub Desktop.
/**
* Update relative `require`s in Node.js to use the minimal number of `../` path
* pieces.
*
* Usage:
*
* ```shell
* node relative-require.js path/to/my/file.js
* ```
*/
const fs = require('fs')
const path = require('path')
const filename = path.join(process.cwd(), process.argv[process.argv.length - 1])
const contents = fs.readFileSync(filename, 'utf8')
const requires = new Set()
const pattern = /require\s*\(\s*(".*"|'.*')\s*\)/g
let mappedContents = contents
let result
/**
* `pattern` is stateful. Use `RegExp#exec` to iterate through the matches and
* get the first capture group.
*
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec}
*/
while (result = pattern.exec(contents)) {
// Store `require(...)`s in a `Set` to prevent duplicate entries
requires.add(result[1].slice(1, result[1].length - 1))
}
for (const r of requires.values()) {
if (r[0] === '.') {
mappedContents = mappedContents.replace(
new RegExp(r, 'g'),
path.relative(
filename,
path.resolve(path.dirname(filename), r)
)
)
}
}
console.log(mappedContents)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment