Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sorenlouv/a17bbfb9b127fcab1dfaf813ae558090 to your computer and use it in GitHub Desktop.
Save sorenlouv/a17bbfb9b127fcab1dfaf813ae558090 to your computer and use it in GitHub Desktop.
Replace webpack aliases with relative paths
// Usage: jscodeshift -t replace-webpack-alias-with-relative-path.js ./kibana/x-pack/plugins ./kibana/src
const path = require('path');
const URI = require('urijs');
function getRelativePath(currentFilePath, dependencyPath) {
return URI(dependencyPath)
.relativeTo(currentFilePath)
.toString();
}
// necessary due to: https://github.com/facebook/jscodeshift/issues/44
function retainFirstComment(transformer) {
return (file, api) => {
const j = api.jscodeshift;
const root = j(file.source);
const getFirstNode = root => root.find(j.Program).get('body', 0).node;
const firstNode = getFirstNode(root);
const { comments } = firstNode;
const newRoot = transformer(file, api);
const firstNode2 = getFirstNode(newRoot);
if (firstNode2 !== firstNode) {
firstNode2.comments = comments;
}
return newRoot.toSource({quote: 'single'});
};
}
const transformer = retainFirstComment((file, api) => {
const j = api.jscodeshift;
const absolutePathToDep = '/Users/sqren/elastic/kibana/src/ui/public/chrome';
const absolutePathToCurrentFile = path.resolve(process.cwd(), file.path);
const root = j(file.source);
const importDeclarations = root.find(j.ImportDeclaration).find(j.Literal);
root
.find(j.ImportDeclaration)
.filter(path => path.value.source.value === 'ui/chrome')
.forEach(path => {
const relativePath = getRelativePath(
absolutePathToCurrentFile,
absolutePathToDep
);
return j(path).replaceWith(
j.importDeclaration(path.node.specifiers, j.literal(relativePath))
);
});
return root;
});
export default transformer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment