loaderOptionsPlugin.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const isEmpty = require("lodash/isEmpty");
  2. const findPluginsByName = require("../../utils/ast-utils").findPluginsByName;
  3. const createOrUpdatePluginByName = require("../../utils/ast-utils")
  4. .createOrUpdatePluginByName;
  5. const safeTraverse = require("../../utils/ast-utils").safeTraverse;
  6. /**
  7. *
  8. * Transform which adds context information for old loaders by injecting a `LoaderOptionsPlugin`
  9. *
  10. * @param {Object} j - jscodeshift top-level import
  11. * @param {Node} ast - jscodeshift ast to transform
  12. * @returns {Node} ast - jscodeshift ast
  13. *
  14. */
  15. module.exports = function(j, ast) {
  16. const loaderOptions = {};
  17. // If there is debug: true, set debug: true in the plugin
  18. if (ast.find(j.Identifier, { name: "debug" }).size()) {
  19. loaderOptions.debug = true;
  20. ast.find(j.Identifier, { name: "debug" }).forEach(p => {
  21. p.parent.prune();
  22. });
  23. }
  24. // If there is UglifyJsPlugin, set minimize: true
  25. if (findPluginsByName(j, ast, ["webpack.optimize.UglifyJsPlugin"]).size()) {
  26. loaderOptions.minimize = true;
  27. }
  28. return ast
  29. .find(j.ArrayExpression)
  30. .filter(
  31. path =>
  32. safeTraverse(path, ["parent", "value", "key", "name"]) === "plugins"
  33. )
  34. .forEach(path => {
  35. !isEmpty(loaderOptions) &&
  36. createOrUpdatePluginByName(
  37. j,
  38. path,
  39. "webpack.LoaderOptionsPlugin",
  40. loaderOptions
  41. );
  42. });
  43. };