Skip to content

Instantly share code, notes, and snippets.

@dbrugne
Created June 14, 2017 08:25
Show Gist options
  • Save dbrugne/9e3ac2f1dec314e20a2066799aab12ce to your computer and use it in GitHub Desktop.
Save dbrugne/9e3ac2f1dec314e20a2066799aab12ce to your computer and use it in GitHub Desktop.
jscodeshift to replace depedencies module import with local module import
import { parse } from 'path';
/**
* Search for
*
* import ... from 'mydependency';
*
* And replace with a relative import:
*
* import ... from '.../mydependency';
*
* Following example works on a 'lib' folder and go back in folder tree to import a lib/mylocalmodule.js file.
* Example, in lib/sub/folder/file.js replaces:
*
* import m from 'mydependency';
*
* With:
*
* import m from '../../mylocalmodule';
*
* Run with: jscodeshift -t depedencyToLocalTransform.js lib
*/
module.exports = function (file, api) {
const j = api.jscodeshift;
const { dir } = parse(file.path);
const levels = String(dir).split('/').length - 1; // - 1 should vary depending mylocalmodule.js location
let newPath = 'mylocalmodule';
for (let i = 1; i <= levels; i += 1) {
newPath = `../${newPath}`;
}
return j(file.source)
.find(j.ImportDeclaration, { source: { type: 'Literal', value: 'mydependency' } })
.forEach((path) => {
const { node } = path;
node.source = `'${newPath}'`;
return node;
})
.toSource();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment