resolve.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. *
  3. * Transform which consolidates the `resolve.root` configuration option into the `resolve.modules` array
  4. *
  5. * @param {Object} j - jscodeshift top-level import
  6. * @param {Node} ast - jscodeshift ast to transform
  7. * @returns {Node} ast - jscodeshift ast
  8. */
  9. module.exports = function transformer(j, ast) {
  10. const getRootVal = p => {
  11. return p.node.value.properties.filter(prop => prop.key.name === "root")[0];
  12. };
  13. const getRootIndex = p => {
  14. return p.node.value.properties.reduce((rootIndex, prop, index) => {
  15. return prop.key.name === "root" ? index : rootIndex;
  16. }, -1);
  17. };
  18. const isModulePresent = p => {
  19. const modules = p.node.value.properties.filter(
  20. prop => prop.key.name === "modules"
  21. );
  22. return modules.length > 0 && modules[0];
  23. };
  24. /**
  25. *
  26. * Add a `modules` property to the `resolve` object or update the existing one
  27. * based on what is already in `resolve.root`
  28. *
  29. * @param {Node} p - ast node that represents the `resolve` property
  30. * @returns {Node} p - ast node that represents the updated `resolve` property
  31. */
  32. const createModuleArray = p => {
  33. const rootVal = getRootVal(p);
  34. let modulesVal = null;
  35. if (rootVal.value.type === "ArrayExpression") {
  36. modulesVal = rootVal.value.elements;
  37. } else {
  38. modulesVal = [rootVal.value];
  39. }
  40. let module = isModulePresent(p);
  41. if (!module) {
  42. module = j.property(
  43. "init",
  44. j.identifier("modules"),
  45. j.arrayExpression(modulesVal)
  46. );
  47. p.node.value.properties = p.node.value.properties.concat([module]);
  48. } else {
  49. module.value.elements = module.value.elements.concat(modulesVal);
  50. }
  51. const rootIndex = getRootIndex(p);
  52. p.node.value.properties.splice(rootIndex, 1);
  53. return p;
  54. };
  55. return ast
  56. .find(j.Property)
  57. .filter(p => {
  58. return (
  59. p.node.key.name === "resolve" &&
  60. p.node.value.properties.filter(prop => prop.key.name === "root")
  61. .length === 1
  62. );
  63. })
  64. .forEach(createModuleArray);
  65. };