webpack-dev-server.js 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. #!/usr/bin/env node
  2. /* Based on webpack/bin/webpack.js */
  3. /* eslint-disable no-console */
  4. "use strict";
  5. /**
  6. * @param {string} command process to run
  7. * @param {string[]} args command line arguments
  8. * @returns {Promise<void>} promise
  9. */
  10. const runCommand = (command, args) => {
  11. const cp = require("child_process");
  12. return new Promise((resolve, reject) => {
  13. const executedCommand = cp.spawn(command, args, {
  14. stdio: "inherit",
  15. shell: true,
  16. });
  17. executedCommand.on("error", (error) => {
  18. reject(error);
  19. });
  20. executedCommand.on("exit", (code) => {
  21. if (code === 0) {
  22. resolve();
  23. } else {
  24. reject();
  25. }
  26. });
  27. });
  28. };
  29. /**
  30. * @param {string} packageName name of the package
  31. * @returns {boolean} is the package installed?
  32. */
  33. const isInstalled = (packageName) => {
  34. if (process.versions.pnp) {
  35. return true;
  36. }
  37. const path = require("path");
  38. const fs = require("graceful-fs");
  39. let dir = __dirname;
  40. do {
  41. try {
  42. if (
  43. fs.statSync(path.join(dir, "node_modules", packageName)).isDirectory()
  44. ) {
  45. return true;
  46. }
  47. } catch (_error) {
  48. // Nothing
  49. }
  50. // eslint-disable-next-line no-cond-assign
  51. } while (dir !== (dir = path.dirname(dir)));
  52. return false;
  53. };
  54. /**
  55. * @param {CliOption} cli options
  56. * @returns {void}
  57. */
  58. const runCli = (cli) => {
  59. if (cli.preprocess) {
  60. cli.preprocess();
  61. }
  62. const path = require("path");
  63. const pkgPath = require.resolve(`${cli.package}/package.json`);
  64. // eslint-disable-next-line import/no-dynamic-require
  65. const pkg = require(pkgPath);
  66. // eslint-disable-next-line import/no-dynamic-require
  67. require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]));
  68. };
  69. /**
  70. * @typedef {Object} CliOption
  71. * @property {string} name display name
  72. * @property {string} package npm package name
  73. * @property {string} binName name of the executable file
  74. * @property {boolean} installed currently installed?
  75. * @property {string} url homepage
  76. * @property {function} preprocess preprocessor
  77. */
  78. /** @type {CliOption} */
  79. const cli = {
  80. name: "webpack-cli",
  81. package: "webpack-cli",
  82. binName: "webpack-cli",
  83. installed: isInstalled("webpack-cli"),
  84. url: "https://github.com/webpack/webpack-cli",
  85. preprocess() {
  86. process.argv.splice(2, 0, "serve");
  87. },
  88. };
  89. if (!cli.installed) {
  90. const path = require("path");
  91. const fs = require("graceful-fs");
  92. const readLine = require("readline");
  93. const notify = `CLI for webpack must be installed.\n ${cli.name} (${cli.url})\n`;
  94. console.error(notify);
  95. /**
  96. * @type {string}
  97. */
  98. let packageManager;
  99. if (fs.existsSync(path.resolve(process.cwd(), "yarn.lock"))) {
  100. packageManager = "yarn";
  101. } else if (fs.existsSync(path.resolve(process.cwd(), "pnpm-lock.yaml"))) {
  102. packageManager = "pnpm";
  103. } else {
  104. packageManager = "npm";
  105. }
  106. const installOptions = [packageManager === "yarn" ? "add" : "install", "-D"];
  107. console.error(
  108. `We will use "${packageManager}" to install the CLI via "${packageManager} ${installOptions.join(
  109. " "
  110. )} ${cli.package}".`
  111. );
  112. const question = `Do you want to install 'webpack-cli' (yes/no): `;
  113. const questionInterface = readLine.createInterface({
  114. input: process.stdin,
  115. output: process.stderr,
  116. });
  117. // In certain scenarios (e.g. when STDIN is not in terminal mode), the callback function will not be
  118. // executed. Setting the exit code here to ensure the script exits correctly in those cases. The callback
  119. // function is responsible for clearing the exit code if the user wishes to install webpack-cli.
  120. process.exitCode = 1;
  121. questionInterface.question(question, (answer) => {
  122. questionInterface.close();
  123. const normalizedAnswer = answer.toLowerCase().startsWith("y");
  124. if (!normalizedAnswer) {
  125. console.error(
  126. "You need to install 'webpack-cli' to use webpack via CLI.\n" +
  127. "You can also install the CLI manually."
  128. );
  129. return;
  130. }
  131. process.exitCode = 0;
  132. console.log(
  133. `Installing '${
  134. cli.package
  135. }' (running '${packageManager} ${installOptions.join(" ")} ${
  136. cli.package
  137. }')...`
  138. );
  139. runCommand(packageManager, installOptions.concat(cli.package))
  140. .then(() => {
  141. runCli(cli);
  142. })
  143. .catch((error) => {
  144. console.error(error);
  145. process.exitCode = 1;
  146. });
  147. });
  148. } else {
  149. runCli(cli);
  150. }