modify-config-helper.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. "use strict";
  2. const fs = require("fs");
  3. const path = require("path");
  4. const chalk = require("chalk");
  5. const yeoman = require("yeoman-environment");
  6. const runTransform = require("../init/index");
  7. const Generator = require("yeoman-generator");
  8. /**
  9. *
  10. * Looks up the webpack.config in the user's path and runs a given
  11. * generator scaffold followed up by a transform
  12. *
  13. * @param {String} action — action to be done (add, remove, update, init)
  14. * @param {Class} name - Name for the given function
  15. * @returns {Function} runTransform - Returns a transformation instance
  16. */
  17. module.exports = function modifyHelperUtil(action, generator, packages) {
  18. let configPath = path.resolve(process.cwd(), "webpack.config.js");
  19. const webpackConfigExists = fs.existsSync(configPath);
  20. if (!webpackConfigExists) {
  21. configPath = null;
  22. }
  23. const env = yeoman.createEnv("webpack", null);
  24. const generatorName = `webpack-${action}-generator`;
  25. if (!generator) {
  26. generator = class extends Generator {
  27. initializing() {
  28. packages.forEach(pkgPath => {
  29. return this.composeWith(require.resolve(pkgPath));
  30. });
  31. }
  32. };
  33. }
  34. env.registerStub(generator, generatorName);
  35. env.run(generatorName).on("end", () => {
  36. let configModule;
  37. try {
  38. const configPath = path.resolve(process.cwd(), ".yo-rc.json");
  39. configModule = require(configPath);
  40. // Change structure of the config to be transformed
  41. let tmpConfig = {};
  42. Object.keys(configModule).forEach(prop => {
  43. const configs = Object.keys(configModule[prop].configuration);
  44. configs.forEach(config => {
  45. tmpConfig[config] = configModule[prop].configuration[config];
  46. });
  47. });
  48. configModule = tmpConfig;
  49. } catch (err) {
  50. console.error(
  51. chalk.red("\nCould not find a yeoman configuration file.\n")
  52. );
  53. console.error(
  54. chalk.red(
  55. "\nPlease make sure to use 'this.config.set('configuration', this.configuration);' at the end of the generator.\n"
  56. )
  57. );
  58. Error.stackTraceLimit = 0;
  59. process.exitCode = -1;
  60. }
  61. const config = Object.assign(
  62. {
  63. configFile: !configPath ? null : fs.readFileSync(configPath, "utf8"),
  64. configPath: configPath
  65. },
  66. configModule
  67. );
  68. return runTransform(config, action);
  69. });
  70. };