webpack-dev-server.js 4.8 KB

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