extractTextPlugin.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const utils = require("../../utils/ast-utils");
  2. /**
  3. *
  4. * Check whether `node` is the invocation of the plugin denoted by `pluginName`
  5. *
  6. * @param {Object} j - jscodeshift top-level import
  7. * @param {Node} node - ast node to check
  8. * @param {String} pluginName - name of the plugin
  9. * @returns {Boolean} isPluginInvocation - whether `node` is the invocation of the plugin denoted by `pluginName`
  10. */
  11. function findInvocation(j, node, pluginName) {
  12. let found = false;
  13. found =
  14. j(node)
  15. .find(j.MemberExpression)
  16. .filter(p => p.get("object").value.name === pluginName)
  17. .size() > 0;
  18. return found;
  19. }
  20. /**
  21. *
  22. * Transform for ExtractTextPlugin arguments. Consolidates arguments into single options object.
  23. *
  24. * @param {Object} j - jscodeshift top-level import
  25. * @param {Node} ast - jscodeshift ast to transform
  26. * @returns {Node} ast - jscodeshift ast
  27. */
  28. module.exports = function(j, ast) {
  29. const changeArguments = function(p) {
  30. const args = p.value.arguments;
  31. const literalArgs = args.filter(p => utils.isType(p, "Literal"));
  32. if (literalArgs && literalArgs.length > 1) {
  33. const newArgs = j.objectExpression(
  34. literalArgs.map((p, index) =>
  35. utils.createProperty(j, index === 0 ? "fallback" : "use", p.value)
  36. )
  37. );
  38. p.value.arguments = [newArgs];
  39. }
  40. return p;
  41. };
  42. const name = utils.findVariableToPlugin(
  43. j,
  44. ast,
  45. "extract-text-webpack-plugin"
  46. );
  47. if (!name) return ast;
  48. return ast
  49. .find(j.CallExpression)
  50. .filter(p => findInvocation(j, p, name))
  51. .forEach(changeArguments);
  52. };