webpack.js 4.4 KB

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