webpack-dev-server.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. // https://github.com/nodejs/node/blob/v18.9.1/lib/internal/modules/cjs/loader.js#L1274
  53. // @ts-ignore
  54. for (const internalPath of require("module").globalPaths) {
  55. try {
  56. if (fs.statSync(path.join(internalPath, packageName)).isDirectory()) {
  57. return true;
  58. }
  59. } catch (_error) {
  60. // Nothing
  61. }
  62. }
  63. return false;
  64. };
  65. /**
  66. * @param {CliOption} cli options
  67. * @returns {void}
  68. */
  69. const runCli = (cli) => {
  70. if (cli.preprocess) {
  71. cli.preprocess();
  72. }
  73. const path = require("path");
  74. const pkgPath = require.resolve(`${cli.package}/package.json`);
  75. // eslint-disable-next-line import/no-dynamic-require
  76. const pkg = require(pkgPath);
  77. // eslint-disable-next-line import/no-dynamic-require
  78. require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]));
  79. };
  80. /**
  81. * @typedef {Object} CliOption
  82. * @property {string} name display name
  83. * @property {string} package npm package name
  84. * @property {string} binName name of the executable file
  85. * @property {boolean} installed currently installed?
  86. * @property {string} url homepage
  87. * @property {function} preprocess preprocessor
  88. */
  89. /** @type {CliOption} */
  90. const cli = {
  91. name: "webpack-cli",
  92. package: "webpack-cli",
  93. binName: "webpack-cli",
  94. installed: isInstalled("webpack-cli"),
  95. url: "https://github.com/webpack/webpack-cli",
  96. preprocess() {
  97. process.argv.splice(2, 0, "serve");
  98. },
  99. };
  100. if (!cli.installed) {
  101. const path = require("path");
  102. const fs = require("graceful-fs");
  103. const readLine = require("readline");
  104. const notify = `CLI for webpack must be installed.\n ${cli.name} (${cli.url})\n`;
  105. console.error(notify);
  106. /**
  107. * @type {string}
  108. */
  109. let packageManager;
  110. if (fs.existsSync(path.resolve(process.cwd(), "yarn.lock"))) {
  111. packageManager = "yarn";
  112. } else if (fs.existsSync(path.resolve(process.cwd(), "pnpm-lock.yaml"))) {
  113. packageManager = "pnpm";
  114. } else {
  115. packageManager = "npm";
  116. }
  117. const installOptions = [packageManager === "yarn" ? "add" : "install", "-D"];
  118. console.error(
  119. `We will use "${packageManager}" to install the CLI via "${packageManager} ${installOptions.join(
  120. " "
  121. )} ${cli.package}".`
  122. );
  123. const question = `Do you want to install 'webpack-cli' (yes/no): `;
  124. const questionInterface = readLine.createInterface({
  125. input: process.stdin,
  126. output: process.stderr,
  127. });
  128. // In certain scenarios (e.g. when STDIN is not in terminal mode), the callback function will not be
  129. // executed. Setting the exit code here to ensure the script exits correctly in those cases. The callback
  130. // function is responsible for clearing the exit code if the user wishes to install webpack-cli.
  131. process.exitCode = 1;
  132. questionInterface.question(question, (answer) => {
  133. questionInterface.close();
  134. const normalizedAnswer = answer.toLowerCase().startsWith("y");
  135. if (!normalizedAnswer) {
  136. console.error(
  137. "You need to install 'webpack-cli' to use webpack via CLI.\n" +
  138. "You can also install the CLI manually."
  139. );
  140. return;
  141. }
  142. process.exitCode = 0;
  143. console.log(
  144. `Installing '${
  145. cli.package
  146. }' (running '${packageManager} ${installOptions.join(" ")} ${
  147. cli.package
  148. }')...`
  149. );
  150. runCommand(packageManager, installOptions.concat(cli.package))
  151. .then(() => {
  152. runCli(cli);
  153. })
  154. .catch((error) => {
  155. console.error(error);
  156. process.exitCode = 1;
  157. });
  158. });
  159. } else {
  160. runCli(cli);
  161. }