convert-argv.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. const path = require("path");
  2. const fs = require("fs");
  3. fs.existsSync = fs.existsSync || path.existsSync;
  4. const interpret = require("interpret");
  5. const prepareOptions = require("./prepareOptions");
  6. const webpackConfigurationSchema = require("./webpackConfigurationSchema.json");
  7. const validateSchema = require("webpack").validateSchema;
  8. const WebpackOptionsValidationError = require("webpack").WebpackOptionsValidationError;
  9. const findup = require("findup-sync");
  10. module.exports = function(...args) {
  11. const argv = args[1] || args[0];
  12. const options = [];
  13. // Shortcuts
  14. if (argv.d) {
  15. argv.debug = true;
  16. argv["output-pathinfo"] = true;
  17. if (!argv.devtool) {
  18. argv.devtool = "eval-cheap-module-source-map";
  19. }
  20. if (!argv.mode) {
  21. argv.mode = "development";
  22. }
  23. }
  24. if (argv.p) {
  25. argv["optimize-minimize"] = true;
  26. argv["define"] = [].concat(argv["define"] || []).concat("process.env.NODE_ENV=\"production\"");
  27. if (!argv.mode) {
  28. argv.mode = "production";
  29. }
  30. }
  31. if (argv.output) {
  32. let output = argv.output;
  33. if (!path.isAbsolute(argv.o)) {
  34. output = path.resolve(process.cwd(), output);
  35. }
  36. argv["output-filename"] = path.basename(output);
  37. argv["output-path"] = path.dirname(output);
  38. }
  39. let configFileLoaded = false;
  40. let configFiles = [];
  41. const extensions = Object.keys(interpret.extensions).sort(function(a, b) {
  42. return a === ".js" ? -1 : b === ".js" ? 1 : a.length - b.length;
  43. });
  44. let i;
  45. if (argv.config) {
  46. const getConfigExtension = function getConfigExtension(configPath) {
  47. for (i = extensions.length - 1; i >= 0; i--) {
  48. const tmpExt = extensions[i];
  49. if (configPath.indexOf(tmpExt, configPath.length - tmpExt.length) > -1) {
  50. return tmpExt;
  51. }
  52. }
  53. return path.extname(configPath);
  54. };
  55. const mapConfigArg = function mapConfigArg(configArg) {
  56. const resolvedPath = path.resolve(configArg);
  57. const extension = getConfigExtension(resolvedPath);
  58. return {
  59. path: resolvedPath,
  60. ext: extension
  61. };
  62. };
  63. const configArgList = Array.isArray(argv.config) ? argv.config : [argv.config];
  64. configFiles = configArgList.map(mapConfigArg);
  65. } else {
  66. const defaultConfigFileNames = ["webpack.config", "webpackfile"].join("|");
  67. const webpackConfigFileRegExp = `(${defaultConfigFileNames})(${extensions.join("|")})`;
  68. const pathToWebpackConfig = findup(webpackConfigFileRegExp);
  69. if (pathToWebpackConfig) {
  70. const resolvedPath = path.resolve(pathToWebpackConfig);
  71. const actualConfigFileName = path.basename(resolvedPath);
  72. const ext = actualConfigFileName.replace(new RegExp(defaultConfigFileNames), "");
  73. configFiles.push({
  74. path: resolvedPath,
  75. ext
  76. });
  77. }
  78. }
  79. if (configFiles.length > 0) {
  80. const registerCompiler = function registerCompiler(moduleDescriptor) {
  81. if (moduleDescriptor) {
  82. if (typeof moduleDescriptor === "string") {
  83. require(moduleDescriptor);
  84. } else if (!Array.isArray(moduleDescriptor)) {
  85. moduleDescriptor.register(require(moduleDescriptor.module));
  86. } else {
  87. for (let i = 0; i < moduleDescriptor.length; i++) {
  88. try {
  89. registerCompiler(moduleDescriptor[i]);
  90. break;
  91. } catch (e) {
  92. // do nothing
  93. }
  94. }
  95. }
  96. }
  97. };
  98. const requireConfig = function requireConfig(configPath) {
  99. let options = (function WEBPACK_OPTIONS() {
  100. if (argv.configRegister && argv.configRegister.length) {
  101. module.paths.unshift(path.resolve(process.cwd(), "node_modules"), process.cwd());
  102. argv.configRegister.forEach(dep => {
  103. require(dep);
  104. });
  105. return require(configPath);
  106. } else {
  107. return require(configPath);
  108. }
  109. })();
  110. options = prepareOptions(options, argv);
  111. return options;
  112. };
  113. configFiles.forEach(function(file) {
  114. registerCompiler(interpret.extensions[file.ext]);
  115. options.push(requireConfig(file.path));
  116. });
  117. configFileLoaded = true;
  118. }
  119. if (!configFileLoaded) {
  120. return processConfiguredOptions({});
  121. } else if (options.length === 1) {
  122. return processConfiguredOptions(options[0]);
  123. } else {
  124. return processConfiguredOptions(options);
  125. }
  126. function processConfiguredOptions(options) {
  127. const webpackConfigurationValidationErrors = validateSchema(webpackConfigurationSchema, options);
  128. if (webpackConfigurationValidationErrors.length) {
  129. const error = new WebpackOptionsValidationError(webpackConfigurationValidationErrors);
  130. console.error(error.message, `\nReceived: ${typeof options} : ${JSON.stringify(options, null, 2)}`);
  131. process.exit(-1); // eslint-disable-line
  132. }
  133. // process Promise
  134. if (typeof options.then === "function") {
  135. return options.then(processConfiguredOptions);
  136. }
  137. // process ES6 default
  138. if (typeof options === "object" && typeof options.default === "object") {
  139. return processConfiguredOptions(options.default);
  140. }
  141. // filter multi-config by name
  142. if (Array.isArray(options) && argv["config-name"]) {
  143. const namedOptions = options.filter(function(opt) {
  144. return opt.name === argv["config-name"];
  145. });
  146. if (namedOptions.length === 0) {
  147. console.error("Configuration with name '" + argv["config-name"] + "' was not found.");
  148. process.exit(-1); // eslint-disable-line
  149. } else if (namedOptions.length === 1) {
  150. return processConfiguredOptions(namedOptions[0]);
  151. }
  152. options = namedOptions;
  153. }
  154. if (Array.isArray(options)) {
  155. options.forEach(processOptions);
  156. } else {
  157. processOptions(options);
  158. }
  159. if (argv.context) {
  160. options.context = path.resolve(argv.context);
  161. }
  162. if (!options.context) {
  163. options.context = process.cwd();
  164. }
  165. if (argv.watch) {
  166. options.watch = true;
  167. }
  168. if (argv["watch-aggregate-timeout"]) {
  169. options.watchOptions = options.watchOptions || {};
  170. options.watchOptions.aggregateTimeout = +argv["watch-aggregate-timeout"];
  171. }
  172. if (typeof argv["watch-poll"] !== "undefined") {
  173. options.watchOptions = options.watchOptions || {};
  174. if (argv["watch-poll"] === "true" || argv["watch-poll"] === "") options.watchOptions.poll = true;
  175. else if (!isNaN(argv["watch-poll"])) options.watchOptions.poll = +argv["watch-poll"];
  176. }
  177. if (argv["watch-stdin"]) {
  178. options.watchOptions = options.watchOptions || {};
  179. options.watchOptions.stdin = true;
  180. options.watch = true;
  181. }
  182. return options;
  183. }
  184. function processOptions(options) {
  185. function ifArg(name, fn, init, finalize) {
  186. const isArray = Array.isArray(argv[name]);
  187. const isSet = typeof argv[name] !== "undefined" && argv[name] !== null;
  188. if (!isArray && !isSet) return;
  189. init && init();
  190. if (isArray) argv[name].forEach(fn);
  191. else if (isSet) fn(argv[name], -1);
  192. finalize && finalize();
  193. }
  194. function ifArgPair(name, fn, init, finalize) {
  195. ifArg(
  196. name,
  197. function(content, idx) {
  198. const i = content.indexOf("=");
  199. if (i < 0) {
  200. return fn(null, content, idx);
  201. } else {
  202. return fn(content.substr(0, i), content.substr(i + 1), idx);
  203. }
  204. },
  205. init,
  206. finalize
  207. );
  208. }
  209. function ifBooleanArg(name, fn) {
  210. ifArg(name, function(bool) {
  211. if (bool) {
  212. fn();
  213. }
  214. });
  215. }
  216. function mapArgToBoolean(name, optionName) {
  217. ifArg(name, function(bool) {
  218. if (bool === true) options[optionName || name] = true;
  219. else if (bool === false) options[optionName || name] = false;
  220. });
  221. }
  222. function loadPlugin(name) {
  223. const loadUtils = require("loader-utils");
  224. let args;
  225. try {
  226. const p = name && name.indexOf("?");
  227. if (p > -1) {
  228. args = loadUtils.parseQuery(name.substring(p));
  229. name = name.substring(0, p);
  230. }
  231. } catch (e) {
  232. console.log("Invalid plugin arguments " + name + " (" + e + ").");
  233. process.exit(-1); // eslint-disable-line
  234. }
  235. let path;
  236. try {
  237. const resolve = require("enhanced-resolve");
  238. path = resolve.sync(process.cwd(), name);
  239. } catch (e) {
  240. console.log("Cannot resolve plugin " + name + ".");
  241. process.exit(-1); // eslint-disable-line
  242. }
  243. let Plugin;
  244. try {
  245. Plugin = require(path);
  246. } catch (e) {
  247. console.log("Cannot load plugin " + name + ". (" + path + ")");
  248. throw e;
  249. }
  250. try {
  251. return new Plugin(args);
  252. } catch (e) {
  253. console.log("Cannot instantiate plugin " + name + ". (" + path + ")");
  254. throw e;
  255. }
  256. }
  257. function ensureObject(parent, name, force) {
  258. if (force || typeof parent[name] !== "object" || parent[name] === null) {
  259. parent[name] = {};
  260. }
  261. }
  262. function ensureArray(parent, name) {
  263. if (!Array.isArray(parent[name])) {
  264. parent[name] = [];
  265. }
  266. }
  267. function addPlugin(options, plugin) {
  268. ensureArray(options, "plugins");
  269. options.plugins.unshift(plugin);
  270. }
  271. ifArg("mode", function(value) {
  272. options.mode = value;
  273. });
  274. ifArgPair(
  275. "entry",
  276. function(name, entry) {
  277. if (typeof options.entry[name] !== "undefined" && options.entry[name] !== null) {
  278. options.entry[name] = [].concat(options.entry[name]).concat(entry);
  279. } else {
  280. options.entry[name] = entry;
  281. }
  282. },
  283. function() {
  284. ensureObject(options, "entry", true);
  285. }
  286. );
  287. function bindRules(arg) {
  288. ifArgPair(
  289. arg,
  290. function(name, binding) {
  291. if (name === null) {
  292. name = binding;
  293. binding += "-loader";
  294. }
  295. const rule = {
  296. test: new RegExp("\\." + name.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + "$"), // eslint-disable-line no-useless-escape
  297. loader: binding
  298. };
  299. if (arg === "module-bind-pre") {
  300. rule.enforce = "pre";
  301. } else if (arg === "module-bind-post") {
  302. rule.enforce = "post";
  303. }
  304. options.module.rules.push(rule);
  305. },
  306. function() {
  307. ensureObject(options, "module");
  308. ensureArray(options.module, "rules");
  309. }
  310. );
  311. }
  312. bindRules("module-bind");
  313. bindRules("module-bind-pre");
  314. bindRules("module-bind-post");
  315. let defineObject;
  316. ifArgPair(
  317. "define",
  318. function(name, value) {
  319. if (name === null) {
  320. name = value;
  321. value = true;
  322. }
  323. defineObject[name] = value;
  324. },
  325. function() {
  326. defineObject = {};
  327. },
  328. function() {
  329. const DefinePlugin = require("webpack").DefinePlugin;
  330. addPlugin(options, new DefinePlugin(defineObject));
  331. }
  332. );
  333. ifArg("output-path", function(value) {
  334. ensureObject(options, "output");
  335. options.output.path = path.resolve(value);
  336. });
  337. ifArg("output-filename", function(value) {
  338. ensureObject(options, "output");
  339. options.output.filename = value;
  340. });
  341. ifArg("output-chunk-filename", function(value) {
  342. ensureObject(options, "output");
  343. options.output.chunkFilename = value;
  344. });
  345. ifArg("output-source-map-filename", function(value) {
  346. ensureObject(options, "output");
  347. options.output.sourceMapFilename = value;
  348. });
  349. ifArg("output-public-path", function(value) {
  350. ensureObject(options, "output");
  351. options.output.publicPath = value;
  352. });
  353. ifArg("output-jsonp-function", function(value) {
  354. ensureObject(options, "output");
  355. options.output.jsonpFunction = value;
  356. });
  357. ifBooleanArg("output-pathinfo", function() {
  358. ensureObject(options, "output");
  359. options.output.pathinfo = true;
  360. });
  361. ifArg("output-library", function(value) {
  362. ensureObject(options, "output");
  363. ensureArray(options.output, "library");
  364. options.output.library.push(value);
  365. });
  366. ifArg("output-library-target", function(value) {
  367. ensureObject(options, "output");
  368. options.output.libraryTarget = value;
  369. });
  370. ifArg("records-input-path", function(value) {
  371. options.recordsInputPath = path.resolve(value);
  372. });
  373. ifArg("records-output-path", function(value) {
  374. options.recordsOutputPath = path.resolve(value);
  375. });
  376. ifArg("records-path", function(value) {
  377. options.recordsPath = path.resolve(value);
  378. });
  379. ifArg("target", function(value) {
  380. options.target = value;
  381. });
  382. mapArgToBoolean("cache");
  383. ifBooleanArg("hot", function() {
  384. const HotModuleReplacementPlugin = require("webpack").HotModuleReplacementPlugin;
  385. addPlugin(options, new HotModuleReplacementPlugin());
  386. });
  387. ifBooleanArg("debug", function() {
  388. const LoaderOptionsPlugin = require("webpack").LoaderOptionsPlugin;
  389. addPlugin(
  390. options,
  391. new LoaderOptionsPlugin({
  392. debug: true
  393. })
  394. );
  395. });
  396. ifArg("devtool", function(value) {
  397. options.devtool = value;
  398. });
  399. function processResolveAlias(arg, key) {
  400. ifArgPair(arg, function(name, value) {
  401. if (!name) {
  402. throw new Error("--" + arg + " <string>=<string>");
  403. }
  404. ensureObject(options, key);
  405. ensureObject(options[key], "alias");
  406. options[key].alias[name] = value;
  407. });
  408. }
  409. processResolveAlias("resolve-alias", "resolve");
  410. processResolveAlias("resolve-loader-alias", "resolveLoader");
  411. ifArg("resolve-extensions", function(value) {
  412. ensureObject(options, "resolve");
  413. if (Array.isArray(value)) {
  414. options.resolve.extensions = value;
  415. } else {
  416. options.resolve.extensions = value.split(/,\s*/);
  417. }
  418. });
  419. ifArg("optimize-max-chunks", function(value) {
  420. const LimitChunkCountPlugin = require("webpack").optimize.LimitChunkCountPlugin;
  421. addPlugin(
  422. options,
  423. new LimitChunkCountPlugin({
  424. maxChunks: parseInt(value, 10)
  425. })
  426. );
  427. });
  428. ifArg("optimize-min-chunk-size", function(value) {
  429. const MinChunkSizePlugin = require("webpack").optimize.MinChunkSizePlugin;
  430. addPlugin(
  431. options,
  432. new MinChunkSizePlugin({
  433. minChunkSize: parseInt(value, 10)
  434. })
  435. );
  436. });
  437. ifBooleanArg("optimize-minimize", function() {
  438. const LoaderOptionsPlugin = require("webpack").LoaderOptionsPlugin;
  439. addPlugin(
  440. options,
  441. new LoaderOptionsPlugin({
  442. minimize: true
  443. })
  444. );
  445. });
  446. ifArg("prefetch", function(request) {
  447. const PrefetchPlugin = require("webpack").PrefetchPlugin;
  448. addPlugin(options, new PrefetchPlugin(request));
  449. });
  450. ifArg("provide", function(value) {
  451. const idx = value.indexOf("=");
  452. let name;
  453. if (idx >= 0) {
  454. name = value.substr(0, idx);
  455. value = value.substr(idx + 1);
  456. } else {
  457. name = value;
  458. }
  459. const ProvidePlugin = require("webpack").ProvidePlugin;
  460. addPlugin(options, new ProvidePlugin(name, value));
  461. });
  462. ifArg("plugin", function(value) {
  463. addPlugin(options, loadPlugin(value));
  464. });
  465. mapArgToBoolean("bail");
  466. mapArgToBoolean("profile");
  467. if (argv._.length > 0) {
  468. ensureObject(options, "entry", true);
  469. const addTo = function addTo(name, entry) {
  470. if (options.entry[name]) {
  471. if (!Array.isArray(options.entry[name])) {
  472. options.entry[name] = [options.entry[name]];
  473. }
  474. options.entry[name].push(entry);
  475. } else {
  476. options.entry[name] = entry;
  477. }
  478. };
  479. argv._.forEach(function(content) {
  480. const i = content.indexOf("=");
  481. const j = content.indexOf("?");
  482. if (i < 0 || (j >= 0 && j < i)) {
  483. const resolved = path.resolve(content);
  484. if (fs.existsSync(resolved)) {
  485. addTo("main", `${resolved}${fs.statSync(resolved).isDirectory() ? path.sep : ""}`);
  486. } else {
  487. addTo("main", content);
  488. }
  489. } else {
  490. addTo(content.substr(0, i), content.substr(i + 1));
  491. }
  492. });
  493. }
  494. }
  495. };