Created
June 9, 2017 04:51
-
-
Save nakamorichi/86c906b2c4032d4426b750d232a4133b to your computer and use it in GitHub Desktop.
Script for converting absolute module paths to relative
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 * as Path from 'path'; | |
import * as recursive from 'recursive-readdir'; | |
import * as Fs from 'fs'; | |
import * as xregexp from 'xregexp'; | |
const root = Path.resolve(__dirname, '..'); | |
recursive(root, ['!*.js'], (error, files) => { | |
files.forEach(file => { | |
const fileContent = Fs.readFileSync(file, 'utf-8'); | |
const regex = xregexp(/require\(["']([^"']*)["']\)/); | |
const modifiedFileContent = xregexp.replace( | |
fileContent, | |
regex, | |
(wholeRequire: any, modulePath: any) => { | |
try { | |
require(modulePath); | |
return wholeRequire; | |
} catch (error) { | |
let newRequirePath = Path.relative(`${file}/..`, `${root}/${modulePath}`); | |
if (newRequirePath[0] !== '.') newRequirePath = './' + newRequirePath; | |
return `require("${newRequirePath}")`; | |
} | |
}, | |
'all', | |
); | |
Fs.writeFileSync(file, modifiedFileContent, 'utf-8'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment