removeJsonLoader.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. const utils = require("../../utils/ast-utils");
  2. /**
  3. *
  4. * Transform which removes the json loader from all possible declarations
  5. *
  6. * @param {Object} j - jscodeshift top-level import
  7. * @param {Node} ast - jscodeshift ast to transform
  8. * @returns {Node} ast - jscodeshift ast
  9. */
  10. module.exports = function(j, ast) {
  11. /**
  12. *
  13. * Remove the loader with name `name` from the given NodePath
  14. *
  15. * @param {Node} path - ast to remove the loader from
  16. * @param {String} name - the name of the loader to remove
  17. *
  18. */
  19. function removeLoaderByName(path, name) {
  20. const loadersNode = path.value.value;
  21. switch (loadersNode.type) {
  22. case j.ArrayExpression.name: {
  23. let loaders = loadersNode.elements.map(p => {
  24. return utils.safeTraverse(p, ["properties", "0", "value", "value"]);
  25. });
  26. const loaderIndex = loaders.indexOf(name);
  27. if (loaders.length && loaderIndex > -1) {
  28. // Remove loader from the array
  29. loaders.splice(loaderIndex, 1);
  30. // and from AST
  31. loadersNode.elements.splice(loaderIndex, 1);
  32. }
  33. // If there are no loaders left, remove the whole Rule object
  34. if (loaders.length === 0) {
  35. j(path.parent).remove();
  36. }
  37. break;
  38. }
  39. case j.Literal.name: {
  40. // If only the loader with the matching name was used
  41. // we can remove the whole Property node completely
  42. if (loadersNode.value === name) {
  43. j(path.parent).remove();
  44. }
  45. break;
  46. }
  47. }
  48. }
  49. function removeLoaders(ast) {
  50. ast
  51. .find(j.Property, { key: { name: "use" } })
  52. .forEach(path => removeLoaderByName(path, "json-loader"));
  53. ast
  54. .find(j.Property, { key: { name: "loader" } })
  55. .forEach(path => removeLoaderByName(path, "json-loader"));
  56. }
  57. const transforms = [removeLoaders];
  58. transforms.forEach(t => t(ast));
  59. return ast;
  60. };