add-generator.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. const Generator = require("yeoman-generator");
  2. const glob = require("glob-all");
  3. const path = require("path");
  4. const Confirm = require("webpack-addons").Confirm;
  5. const List = require("webpack-addons").List;
  6. const Input = require("webpack-addons").Input;
  7. const webpackSchema = require("webpack/schemas/WebpackOptions");
  8. const webpackDevServerSchema = require("webpack-dev-server/lib/optionsSchema.json");
  9. const PROP_TYPES = require("../utils/prop-types");
  10. const getPackageManager = require("../utils/package-manager").getPackageManager;
  11. const npmExists = require("../utils/npm-exists");
  12. const entryQuestions = require("./utils/entry");
  13. /**
  14. *
  15. * Replaces the string with a substring at the given index
  16. * https://gist.github.com/efenacigiray/9367920
  17. *
  18. * @param {String} string - string to be modified
  19. * @param {Number} index - index to replace from
  20. * @param {String} replace - string to replace starting from index
  21. *
  22. * @returns {String} string - The newly mutated string
  23. *
  24. */
  25. function replaceAt(string, index, replace) {
  26. return string.substring(0, index) + replace + string.substring(index + 1);
  27. }
  28. /**
  29. *
  30. * Checks if the given array has a given property
  31. *
  32. * @param {Array} arr - array to check
  33. * @param {String} prop - property to check existence of
  34. *
  35. * @returns {Boolean} hasProp - Boolean indicating if the property
  36. * is present
  37. */
  38. const traverseAndGetProperties = (arr, prop) => {
  39. let hasProp = false;
  40. arr.forEach(p => {
  41. if (p[prop]) {
  42. hasProp = true;
  43. }
  44. });
  45. return hasProp;
  46. };
  47. /**
  48. *
  49. * Generator for adding properties
  50. * @class AddGenerator
  51. * @extends Generator
  52. * @returns {Void} After execution, transforms are triggered
  53. *
  54. */
  55. module.exports = class AddGenerator extends Generator {
  56. constructor(args, opts) {
  57. super(args, opts);
  58. this.dependencies = [];
  59. this.configuration = {
  60. config: {
  61. webpackOptions: {},
  62. topScope: ["const webpack = require('webpack')"]
  63. }
  64. };
  65. }
  66. prompting() {
  67. let done = this.async();
  68. let action;
  69. let self = this;
  70. let manualOrListInput = action =>
  71. Input("actionAnswer", `What do you want to add to ${action}?`);
  72. // first index indicates if it has a deep prop, 2nd indicates what kind of
  73. let isDeepProp = [false, false];
  74. return this.prompt([
  75. List(
  76. "actionType",
  77. "What property do you want to add to?",
  78. Array.from(PROP_TYPES.keys())
  79. )
  80. ])
  81. .then(actionTypeAnswer => {
  82. // Set initial prop, like devtool
  83. this.configuration.config.webpackOptions[
  84. actionTypeAnswer.actionType
  85. ] = null;
  86. // update the action variable, we're using it later
  87. action = actionTypeAnswer.actionType;
  88. })
  89. .then(() => {
  90. if (action === "entry") {
  91. return this.prompt([
  92. Confirm("entryType", "Will your application have multiple bundles?")
  93. ])
  94. .then(entryTypeAnswer => {
  95. // Ask different questions for entry points
  96. return entryQuestions(self, entryTypeAnswer);
  97. })
  98. .then(entryOptions => {
  99. this.configuration.config.webpackOptions.entry = entryOptions;
  100. this.configuration.config.item = action;
  101. });
  102. }
  103. let temp = action;
  104. if (action === "resolveLoader") {
  105. action = "resolve";
  106. }
  107. const webpackSchemaProp = webpackSchema.definitions[action];
  108. /*
  109. * https://github.com/webpack/webpack/blob/next/schemas/WebpackOptions.json
  110. * Find the properties directly in the properties prop, or the anyOf prop
  111. */
  112. let defOrPropDescription = webpackSchemaProp
  113. ? webpackSchemaProp.properties
  114. : webpackSchema.properties[action].properties
  115. ? webpackSchema.properties[action].properties
  116. : webpackSchema.properties[action].anyOf
  117. ? webpackSchema.properties[action].anyOf.filter(
  118. p => p.properties || p.enum
  119. ) // eslint-disable-line
  120. : null;
  121. if (Array.isArray(defOrPropDescription)) {
  122. // Todo: Generalize these to go through the array, then merge enum with props if needed
  123. const hasPropertiesProp = traverseAndGetProperties(
  124. defOrPropDescription,
  125. "properties"
  126. );
  127. const hasEnumProp = traverseAndGetProperties(
  128. defOrPropDescription,
  129. "enum"
  130. );
  131. /* as we know he schema only has two arrays that might hold our values,
  132. * check them for either having arr.enum or arr.properties
  133. */
  134. if (hasPropertiesProp) {
  135. defOrPropDescription =
  136. defOrPropDescription[0].properties ||
  137. defOrPropDescription[1].properties;
  138. if (!defOrPropDescription) {
  139. defOrPropDescription = defOrPropDescription[0].enum;
  140. }
  141. // TODO: manually implement stats and devtools like sourcemaps
  142. } else if (hasEnumProp) {
  143. const originalPropDesc = defOrPropDescription[0].enum;
  144. // Array -> Object -> Merge objects into one for compat in manualOrListInput
  145. defOrPropDescription = Object.keys(defOrPropDescription[0].enum)
  146. .map(p => {
  147. return Object.assign(
  148. {},
  149. {
  150. [originalPropDesc[p]]: "noop"
  151. }
  152. );
  153. })
  154. .reduce((result, currentObject) => {
  155. for (let key in currentObject) {
  156. if (currentObject.hasOwnProperty(key)) {
  157. result[key] = currentObject[key];
  158. }
  159. }
  160. return result;
  161. }, {});
  162. }
  163. }
  164. // WDS has its own schema, so we gonna need to check that too
  165. const webpackDevserverSchemaProp =
  166. action === "devServer" ? webpackDevServerSchema : null;
  167. // Watch has a boolean arg, but we need to append to it manually
  168. if (action === "watch") {
  169. defOrPropDescription = {
  170. true: {},
  171. false: {}
  172. };
  173. }
  174. if (action === "mode") {
  175. defOrPropDescription = {
  176. development: {},
  177. production: {}
  178. };
  179. }
  180. action = temp;
  181. if (action === "resolveLoader") {
  182. defOrPropDescription = Object.assign(defOrPropDescription, {
  183. moduleExtensions: {}
  184. });
  185. }
  186. // If we've got a schema prop or devServer Schema Prop
  187. if (defOrPropDescription || webpackDevserverSchemaProp) {
  188. // Check for properties in definitions[action] or properties[action]
  189. if (defOrPropDescription) {
  190. if (action !== "devtool") {
  191. // Add the option of adding an own variable if the user wants
  192. defOrPropDescription = Object.assign(defOrPropDescription, {
  193. other: {}
  194. });
  195. } else {
  196. // The schema doesn't have the source maps we can prompt, so add those
  197. defOrPropDescription = Object.assign(defOrPropDescription, {
  198. eval: {},
  199. "cheap-eval-source-map": {},
  200. "cheap-module-eval-source-map": {},
  201. "eval-source-map": {},
  202. "cheap-source-map": {},
  203. "cheap-module-source-map": {},
  204. "inline-cheap-source-map": {},
  205. "inline-cheap-module-source-map": {},
  206. "source-map": {},
  207. "inline-source-map": {},
  208. "hidden-source-map": {},
  209. "nosources-source-map": {}
  210. });
  211. }
  212. manualOrListInput = List(
  213. "actionAnswer",
  214. `What do you want to add to ${action}?`,
  215. Object.keys(defOrPropDescription)
  216. );
  217. // We know we're gonna append some deep prop like module.rule
  218. isDeepProp[0] = true;
  219. } else if (webpackDevserverSchemaProp) {
  220. // Append the custom property option
  221. webpackDevserverSchemaProp.properties = Object.assign(
  222. webpackDevserverSchemaProp.properties,
  223. {
  224. other: {}
  225. }
  226. );
  227. manualOrListInput = List(
  228. "actionAnswer",
  229. `What do you want to add to ${action}?`,
  230. Object.keys(webpackDevserverSchemaProp.properties)
  231. );
  232. // We know we are in a devServer.prop scenario
  233. isDeepProp[0] = true;
  234. } else {
  235. // manual input if non-existent
  236. manualOrListInput = manualOrListInput(action);
  237. }
  238. } else {
  239. manualOrListInput = manualOrListInput(action);
  240. }
  241. return this.prompt([manualOrListInput]);
  242. })
  243. .then(answerToAction => {
  244. if (!answerToAction) {
  245. done();
  246. return;
  247. }
  248. /*
  249. * Plugins got their own logic,
  250. * find the names of each natively plugin and check if it matches
  251. */
  252. if (action === "plugins") {
  253. const pluginExist = glob
  254. .sync([
  255. "node_modules/webpack/lib/*Plugin.js",
  256. "node_modules/webpack/lib/**/*Plugin.js"
  257. ])
  258. .map(p =>
  259. p
  260. .split("/")
  261. .pop()
  262. .replace(".js", "")
  263. )
  264. .find(
  265. p => p.toLowerCase().indexOf(answerToAction.actionAnswer) >= 0
  266. );
  267. if (pluginExist) {
  268. this.configuration.config.item = pluginExist;
  269. const pluginsSchemaPath = glob
  270. .sync([
  271. "node_modules/webpack/schemas/plugins/*Plugin.json",
  272. "node_modules/webpack/schemas/plugins/**/*Plugin.json"
  273. ])
  274. .find(
  275. p =>
  276. p
  277. .split("/")
  278. .pop()
  279. .replace(".json", "")
  280. .toLowerCase()
  281. .indexOf(answerToAction.actionAnswer) >= 0
  282. );
  283. if (pluginsSchemaPath) {
  284. const constructorPrefix =
  285. pluginsSchemaPath.indexOf("optimize") >= 0
  286. ? "webpack.optimize"
  287. : "webpack";
  288. const resolvePluginsPath = path.resolve(pluginsSchemaPath);
  289. const pluginSchema = resolvePluginsPath
  290. ? require(resolvePluginsPath)
  291. : null;
  292. let pluginsSchemaProps = ["other"];
  293. if (pluginSchema) {
  294. Object.keys(pluginSchema)
  295. .filter(p => Array.isArray(pluginSchema[p]))
  296. .forEach(p => {
  297. Object.keys(pluginSchema[p]).forEach(n => {
  298. if (pluginSchema[p][n].properties) {
  299. pluginsSchemaProps = Object.keys(
  300. pluginSchema[p][n].properties
  301. );
  302. }
  303. });
  304. });
  305. }
  306. return this.prompt([
  307. List(
  308. "pluginsPropType",
  309. `What property do you want to add ${pluginExist}?`,
  310. pluginsSchemaProps
  311. )
  312. ]).then(pluginsPropAnswer => {
  313. return this.prompt([
  314. Input(
  315. "pluginsPropTypeVal",
  316. `What value should ${pluginExist}.${
  317. pluginsPropAnswer.pluginsPropType
  318. } have?`
  319. )
  320. ]).then(valForProp => {
  321. this.configuration.config.webpackOptions[action] = {
  322. [`${constructorPrefix}.${pluginExist}`]: {
  323. [pluginsPropAnswer.pluginsPropType]:
  324. valForProp.pluginsPropTypeVal
  325. }
  326. };
  327. done();
  328. });
  329. });
  330. } else {
  331. this.configuration.config.webpackOptions[
  332. action
  333. ] = `new webpack.${pluginExist}`;
  334. done();
  335. }
  336. } else {
  337. // If its not in webpack, check npm
  338. npmExists(answerToAction.actionAnswer).then(p => {
  339. if (p) {
  340. this.dependencies.push(answerToAction.actionAnswer);
  341. const normalizePluginName = answerToAction.actionAnswer.replace(
  342. "-webpack-plugin",
  343. "Plugin"
  344. );
  345. const pluginName = replaceAt(
  346. normalizePluginName,
  347. 0,
  348. normalizePluginName.charAt(0).toUpperCase()
  349. );
  350. this.configuration.config.topScope.push(
  351. `const ${pluginName} = require("${
  352. answerToAction.actionAnswer
  353. }")`
  354. );
  355. this.configuration.config.webpackOptions[
  356. action
  357. ] = `new ${pluginName}`;
  358. this.configuration.config.item = answerToAction.actionAnswer;
  359. done();
  360. this.runInstall(getPackageManager(), this.dependencies, {
  361. "save-dev": true
  362. });
  363. } else {
  364. console.error(
  365. answerToAction.actionAnswer,
  366. "doesn't exist on NPM or is built in webpack, please check for any misspellings."
  367. );
  368. process.exit(0);
  369. }
  370. });
  371. }
  372. } else {
  373. // If we're in the scenario with a deep-property
  374. if (isDeepProp[0]) {
  375. isDeepProp[1] = answerToAction.actionAnswer;
  376. if (
  377. isDeepProp[1] !== "other" &&
  378. (action === "devtool" || action === "watch" || action === "mode")
  379. ) {
  380. this.configuration.config.item = action;
  381. this.configuration.config.webpackOptions[action] =
  382. answerToAction.actionAnswer;
  383. done();
  384. return;
  385. }
  386. // Either we are adding directly at the property, else we're in a prop.theOne scenario
  387. const actionMessage =
  388. isDeepProp[1] === "other"
  389. ? `What do you want the key on ${action} to be? (press enter if you want it directly as a value on the property)`
  390. : `What do you want the value of ${isDeepProp[1]} to be?`;
  391. this.prompt([Input("deepProp", actionMessage)]).then(
  392. deepPropAns => {
  393. // The other option needs to be validated of either being empty or not
  394. if (isDeepProp[1] === "other") {
  395. let othersDeepPropKey = deepPropAns.deepProp
  396. ? `What do you want the value of ${
  397. deepPropAns.deepProp
  398. } to be?` // eslint-disable-line
  399. : `What do you want to be the value of ${action} to be?`;
  400. // Push the answer to the array we have created, so we can use it later
  401. isDeepProp.push(deepPropAns.deepProp);
  402. this.prompt([Input("deepProp", othersDeepPropKey)]).then(
  403. deepPropAns => {
  404. // Check length, if it has none, add the prop directly on the given action
  405. if (isDeepProp[2].length === 0) {
  406. this.configuration.config.item = action;
  407. this.configuration.config.webpackOptions[action] =
  408. deepPropAns.deepProp;
  409. } else {
  410. // If not, we're adding to something like devServer.myProp
  411. this.configuration.config.item =
  412. action + "." + isDeepProp[2];
  413. this.configuration.config.webpackOptions[action] = {
  414. [isDeepProp[2]]: deepPropAns.deepProp
  415. };
  416. }
  417. done();
  418. }
  419. );
  420. } else {
  421. // We got the schema prop, we've correctly prompted it, and can add it directly
  422. this.configuration.config.item = action + "." + isDeepProp[1];
  423. this.configuration.config.webpackOptions[action] = {
  424. [isDeepProp[1]]: deepPropAns.deepProp
  425. };
  426. done();
  427. }
  428. }
  429. );
  430. } else {
  431. // We're asking for input-only
  432. this.configuration.config.item = action;
  433. this.configuration.config.webpackOptions[action] =
  434. answerToAction.actionAnswer;
  435. done();
  436. }
  437. }
  438. });
  439. }
  440. writing() {
  441. this.config.set("configuration", this.configuration);
  442. }
  443. };