webpack-dev-server.js 14 KB

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