convert-argv.js 15 KB

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