webpack-dev-server.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. #!/usr/bin/env node
  2. 'use strict';
  3. /* eslint global-require: off, import/order: off, no-console: off */
  4. require('../lib/polyfills');
  5. const debug = require('debug')('webpack-dev-server');
  6. const fs = require('fs');
  7. const net = require('net');
  8. const path = require('path');
  9. const importLocal = require('import-local');
  10. const open = require('opn');
  11. const portfinder = require('portfinder');
  12. const addDevServerEntrypoints = require('../lib/util/addDevServerEntrypoints');
  13. const createDomain = require('../lib/util/createDomain'); // eslint-disable-line
  14. // Prefer the local installation of webpack-dev-server
  15. if (importLocal(__filename)) {
  16. debug('Using local install of webpack-dev-server');
  17. return;
  18. }
  19. const Server = require('../lib/Server');
  20. const webpack = require('webpack'); // eslint-disable-line
  21. function versionInfo() {
  22. return `webpack-dev-server ${require('../package.json').version}\n` +
  23. `webpack ${require('webpack/package.json').version}`;
  24. }
  25. function colorInfo(useColor, msg) {
  26. if (useColor) {
  27. // Make text blue and bold, so it *pops*
  28. return `\u001b[1m\u001b[34m${msg}\u001b[39m\u001b[22m`;
  29. }
  30. return msg;
  31. }
  32. function colorError(useColor, msg) {
  33. if (useColor) {
  34. // Make text red and bold, so it *pops*
  35. return `\u001b[1m\u001b[31m${msg}\u001b[39m\u001b[22m`;
  36. }
  37. return msg;
  38. }
  39. // eslint-disable-next-line
  40. const defaultTo = (value, def) => value == null ? def : value;
  41. const yargs = require('yargs')
  42. .usage(`${versionInfo()}\nUsage: https://webpack.js.org/configuration/dev-server/`);
  43. require('webpack/bin/config-yargs')(yargs);
  44. // It is important that this is done after the webpack yargs config,
  45. // so it overrides webpack's version info.
  46. yargs
  47. .version(versionInfo());
  48. const ADVANCED_GROUP = 'Advanced options:';
  49. const DISPLAY_GROUP = 'Stats options:';
  50. const SSL_GROUP = 'SSL options:';
  51. const CONNECTION_GROUP = 'Connection options:';
  52. const RESPONSE_GROUP = 'Response options:';
  53. const BASIC_GROUP = 'Basic options:';
  54. // Taken out of yargs because we must know if
  55. // it wasn't given by the user, in which case
  56. // we should use portfinder.
  57. const DEFAULT_PORT = 8080;
  58. yargs.options({
  59. bonjour: {
  60. type: 'boolean',
  61. describe: 'Broadcasts the server via ZeroConf networking on start'
  62. },
  63. lazy: {
  64. type: 'boolean',
  65. describe: 'Lazy'
  66. },
  67. inline: {
  68. type: 'boolean',
  69. default: true,
  70. describe: 'Inline mode (set to false to disable including client scripts like livereload)'
  71. },
  72. progress: {
  73. type: 'boolean',
  74. describe: 'Print compilation progress in percentage',
  75. group: BASIC_GROUP
  76. },
  77. 'hot-only': {
  78. type: 'boolean',
  79. describe: 'Do not refresh page if HMR fails',
  80. group: ADVANCED_GROUP
  81. },
  82. stdin: {
  83. type: 'boolean',
  84. describe: 'close when stdin ends'
  85. },
  86. open: {
  87. type: 'string',
  88. describe: 'Open the default browser, or optionally specify a browser name'
  89. },
  90. useLocalIp: {
  91. type: 'boolean',
  92. describe: 'Open default browser with local IP'
  93. },
  94. 'open-page': {
  95. type: 'string',
  96. describe: 'Open default browser with the specified page',
  97. requiresArg: true
  98. },
  99. color: {
  100. type: 'boolean',
  101. alias: 'colors',
  102. default: function supportsColor() {
  103. return require('supports-color');
  104. },
  105. group: DISPLAY_GROUP,
  106. describe: 'Enables/Disables colors on the console'
  107. },
  108. info: {
  109. type: 'boolean',
  110. group: DISPLAY_GROUP,
  111. default: true,
  112. describe: 'Info'
  113. },
  114. quiet: {
  115. type: 'boolean',
  116. group: DISPLAY_GROUP,
  117. describe: 'Quiet'
  118. },
  119. 'client-log-level': {
  120. type: 'string',
  121. group: DISPLAY_GROUP,
  122. default: 'info',
  123. describe: 'Log level in the browser (info, warning, error or none)'
  124. },
  125. https: {
  126. type: 'boolean',
  127. group: SSL_GROUP,
  128. describe: 'HTTPS'
  129. },
  130. key: {
  131. type: 'string',
  132. describe: 'Path to a SSL key.',
  133. group: SSL_GROUP
  134. },
  135. cert: {
  136. type: 'string',
  137. describe: 'Path to a SSL certificate.',
  138. group: SSL_GROUP
  139. },
  140. cacert: {
  141. type: 'string',
  142. describe: 'Path to a SSL CA certificate.',
  143. group: SSL_GROUP
  144. },
  145. pfx: {
  146. type: 'string',
  147. describe: 'Path to a SSL pfx file.',
  148. group: SSL_GROUP
  149. },
  150. 'pfx-passphrase': {
  151. type: 'string',
  152. describe: 'Passphrase for pfx file.',
  153. group: SSL_GROUP
  154. },
  155. 'content-base': {
  156. type: 'string',
  157. describe: 'A directory or URL to serve HTML content from.',
  158. group: RESPONSE_GROUP
  159. },
  160. 'watch-content-base': {
  161. type: 'boolean',
  162. describe: 'Enable live-reloading of the content-base.',
  163. group: RESPONSE_GROUP
  164. },
  165. 'history-api-fallback': {
  166. type: 'boolean',
  167. describe: 'Fallback to /index.html for Single Page Applications.',
  168. group: RESPONSE_GROUP
  169. },
  170. compress: {
  171. type: 'boolean',
  172. describe: 'Enable gzip compression',
  173. group: RESPONSE_GROUP
  174. },
  175. port: {
  176. describe: 'The port',
  177. group: CONNECTION_GROUP
  178. },
  179. 'disable-host-check': {
  180. type: 'boolean',
  181. describe: 'Will not check the host',
  182. group: CONNECTION_GROUP
  183. },
  184. socket: {
  185. type: 'String',
  186. describe: 'Socket to listen',
  187. group: CONNECTION_GROUP
  188. },
  189. public: {
  190. type: 'string',
  191. describe: 'The public hostname/ip address of the server',
  192. group: CONNECTION_GROUP
  193. },
  194. host: {
  195. type: 'string',
  196. default: 'localhost',
  197. describe: 'The hostname/ip address the server will bind to',
  198. group: CONNECTION_GROUP
  199. },
  200. 'allowed-hosts': {
  201. type: 'string',
  202. describe: 'A comma-delimited string of hosts that are allowed to access the dev server',
  203. group: CONNECTION_GROUP
  204. }
  205. });
  206. const argv = yargs.argv;
  207. const wpOpt = require('webpack/bin/convert-argv')(yargs, argv, {
  208. outputFilename: '/bundle.js'
  209. });
  210. function processOptions(webpackOptions) {
  211. // process Promise
  212. if (typeof webpackOptions.then === 'function') {
  213. webpackOptions.then(processOptions).catch((err) => {
  214. console.error(err.stack || err);
  215. process.exit(); // eslint-disable-line
  216. });
  217. return;
  218. }
  219. const firstWpOpt = Array.isArray(webpackOptions) ? webpackOptions[0] : webpackOptions;
  220. const options = webpackOptions.devServer || firstWpOpt.devServer || {};
  221. if (argv.bonjour) { options.bonjour = true; }
  222. if (argv.host !== 'localhost' || !options.host) { options.host = argv.host; }
  223. if (argv['allowed-hosts']) { options.allowedHosts = argv['allowed-hosts'].split(','); }
  224. if (argv.public) { options.public = argv.public; }
  225. if (argv.socket) { options.socket = argv.socket; }
  226. if (argv.progress) { options.progress = argv.progress; }
  227. if (!options.publicPath) {
  228. // eslint-disable-next-line
  229. options.publicPath = firstWpOpt.output && firstWpOpt.output.publicPath || '';
  230. if (!/^(https?:)?\/\//.test(options.publicPath) && options.publicPath[0] !== '/') {
  231. options.publicPath = `/${options.publicPath}`;
  232. }
  233. }
  234. if (!options.filename) { options.filename = firstWpOpt.output && firstWpOpt.output.filename; }
  235. if (!options.watchOptions) { options.watchOptions = firstWpOpt.watchOptions; }
  236. if (argv.stdin) {
  237. process.stdin.on('end', () => {
  238. process.exit(0); // eslint-disable-line no-process-exit
  239. });
  240. process.stdin.resume();
  241. }
  242. if (!options.hot) { options.hot = argv.hot; }
  243. if (!options.hotOnly) { options.hotOnly = argv['hot-only']; }
  244. if (!options.clientLogLevel) { options.clientLogLevel = argv['client-log-level']; }
  245. // eslint-disable-next-line
  246. if (options.contentBase === undefined) {
  247. if (argv['content-base']) {
  248. options.contentBase = argv['content-base'];
  249. if (Array.isArray(options.contentBase)) {
  250. options.contentBase = options.contentBase.map(val => path.resolve(val));
  251. } else if (/^[0-9]$/.test(options.contentBase)) { options.contentBase = +options.contentBase; } else if (!/^(https?:)?\/\//.test(options.contentBase)) { options.contentBase = path.resolve(options.contentBase); }
  252. // It is possible to disable the contentBase by using `--no-content-base`, which results in arg["content-base"] = false
  253. } else if (argv['content-base'] === false) {
  254. options.contentBase = false;
  255. }
  256. }
  257. if (argv['watch-content-base']) { options.watchContentBase = true; }
  258. if (!options.stats) {
  259. options.stats = {
  260. cached: false,
  261. cachedAssets: false
  262. };
  263. }
  264. if (typeof options.stats === 'object' && typeof options.stats.colors === 'undefined') {
  265. options.stats = Object.assign({}, options.stats, { colors: argv.color });
  266. }
  267. if (argv.lazy) { options.lazy = true; }
  268. if (!argv.info) { options.noInfo = true; }
  269. if (argv.quiet) { options.quiet = true; }
  270. if (argv.https) { options.https = true; }
  271. if (argv.cert) { options.cert = fs.readFileSync(path.resolve(argv.cert)); }
  272. if (argv.key) { options.key = fs.readFileSync(path.resolve(argv.key)); }
  273. if (argv.cacert) { options.ca = fs.readFileSync(path.resolve(argv.cacert)); }
  274. if (argv.pfx) { options.pfx = fs.readFileSync(path.resolve(argv.pfx)); }
  275. if (argv['pfx-passphrase']) { options.pfxPassphrase = argv['pfx-passphrase']; }
  276. if (argv.inline === false) { options.inline = false; }
  277. if (argv['history-api-fallback']) { options.historyApiFallback = true; }
  278. if (argv.compress) { options.compress = true; }
  279. if (argv['disable-host-check']) { options.disableHostCheck = true; }
  280. if (argv['open-page']) {
  281. options.open = true;
  282. options.openPage = argv['open-page'];
  283. }
  284. if (typeof argv.open !== 'undefined') {
  285. options.open = argv.open !== '' ? argv.open : true;
  286. }
  287. if (options.open && !options.openPage) { options.openPage = ''; }
  288. if (argv.useLocalIp) { options.useLocalIp = true; }
  289. // Kind of weird, but ensures prior behavior isn't broken in cases
  290. // that wouldn't throw errors. E.g. both argv.port and options.port
  291. // were specified, but since argv.port is 8080, options.port will be
  292. // tried first instead.
  293. options.port = argv.port === DEFAULT_PORT ? defaultTo(options.port, argv.port) : defaultTo(argv.port, options.port);
  294. if (options.port != null) {
  295. startDevServer(webpackOptions, options);
  296. return;
  297. }
  298. portfinder.basePort = DEFAULT_PORT;
  299. portfinder.getPort((err, port) => {
  300. if (err) throw err;
  301. options.port = port;
  302. startDevServer(webpackOptions, options);
  303. });
  304. }
  305. function startDevServer(webpackOptions, options) {
  306. addDevServerEntrypoints(webpackOptions, options);
  307. let compiler;
  308. try {
  309. compiler = webpack(webpackOptions);
  310. } catch (e) {
  311. if (e instanceof webpack.WebpackOptionsValidationError) {
  312. console.error(colorError(options.stats.colors, e.message));
  313. process.exit(1); // eslint-disable-line
  314. }
  315. throw e;
  316. }
  317. if (options.progress) {
  318. compiler.apply(new webpack.ProgressPlugin({
  319. profile: argv.profile
  320. }));
  321. }
  322. const suffix = (options.inline !== false || options.lazy === true ? '/' : '/webpack-dev-server/');
  323. let server;
  324. try {
  325. server = new Server(compiler, options);
  326. } catch (e) {
  327. const OptionsValidationError = require('../lib/OptionsValidationError');
  328. if (e instanceof OptionsValidationError) {
  329. console.error(colorError(options.stats.colors, e.message));
  330. process.exit(1); // eslint-disable-line
  331. }
  332. throw e;
  333. }
  334. ['SIGINT', 'SIGTERM'].forEach((sig) => {
  335. process.on(sig, () => {
  336. server.close(() => {
  337. process.exit(); // eslint-disable-line no-process-exit
  338. });
  339. });
  340. });
  341. if (options.socket) {
  342. server.listeningApp.on('error', (e) => {
  343. if (e.code === 'EADDRINUSE') {
  344. const clientSocket = new net.Socket();
  345. clientSocket.on('error', (clientError) => {
  346. if (clientError.code === 'ECONNREFUSED') {
  347. // No other server listening on this socket so it can be safely removed
  348. fs.unlinkSync(options.socket);
  349. server.listen(options.socket, options.host, (err) => {
  350. if (err) throw err;
  351. });
  352. }
  353. });
  354. clientSocket.connect({ path: options.socket }, () => {
  355. throw new Error('This socket is already used');
  356. });
  357. }
  358. });
  359. server.listen(options.socket, options.host, (err) => {
  360. if (err) throw err;
  361. // chmod 666 (rw rw rw)
  362. const READ_WRITE = 438;
  363. fs.chmod(options.socket, READ_WRITE, (fsError) => {
  364. if (fsError) throw fsError;
  365. const uri = createDomain(options, server.listeningApp) + suffix;
  366. reportReadiness(uri, options);
  367. });
  368. });
  369. } else {
  370. server.listen(options.port, options.host, (err) => {
  371. if (err) throw err;
  372. if (options.bonjour) broadcastZeroconf(options);
  373. const uri = createDomain(options, server.listeningApp) + suffix;
  374. reportReadiness(uri, options);
  375. });
  376. }
  377. }
  378. function reportReadiness(uri, options) {
  379. const useColor = argv.color;
  380. const contentBase = Array.isArray(options.contentBase) ? options.contentBase.join(', ') : options.contentBase;
  381. if (!options.quiet) {
  382. let startSentence = `Project is running at ${colorInfo(useColor, uri)}`;
  383. if (options.socket) {
  384. startSentence = `Listening to socket at ${colorInfo(useColor, options.socket)}`;
  385. }
  386. console.log((options.progress ? '\n' : '') + startSentence);
  387. console.log(`webpack output is served from ${colorInfo(useColor, options.publicPath)}`);
  388. if (contentBase) { console.log(`Content not from webpack is served from ${colorInfo(useColor, contentBase)}`); }
  389. if (options.historyApiFallback) { console.log(`404s will fallback to ${colorInfo(useColor, options.historyApiFallback.index || '/index.html')}`); }
  390. if (options.bonjour) { console.log('Broadcasting "http" with subtype of "webpack" via ZeroConf DNS (Bonjour)'); }
  391. }
  392. if (options.open) {
  393. let openOptions = {};
  394. let openMessage = 'Unable to open browser';
  395. if (typeof options.open === 'string') {
  396. openOptions = { app: options.open };
  397. openMessage += `: ${options.open}`;
  398. }
  399. open(uri + (options.openPage || ''), openOptions).catch(() => {
  400. console.log(`${openMessage}. If you are running in a headless environment, please do not use the open flag.`);
  401. });
  402. }
  403. }
  404. function broadcastZeroconf(options) {
  405. const bonjour = require('bonjour')();
  406. bonjour.publish({
  407. name: 'Webpack Dev Server',
  408. port: options.port,
  409. type: 'http',
  410. subtypes: ['webpack']
  411. });
  412. process.on('exit', () => {
  413. bonjour.unpublishAll(() => {
  414. bonjour.destroy();
  415. });
  416. });
  417. }
  418. processOptions(wpOpt);