Skip to content

Instantly share code, notes, and snippets.

@nakamorichi
Created June 9, 2017 04:51
Show Gist options
  • Save nakamorichi/86c906b2c4032d4426b750d232a4133b to your computer and use it in GitHub Desktop.
Save nakamorichi/86c906b2c4032d4426b750d232a4133b to your computer and use it in GitHub Desktop.
Script for converting absolute module paths to relative
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