webpack.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. #!/usr/bin/env node
  2. /**
  3. * @param {string} command process to run
  4. * @param {string[]} args command line arguments
  5. * @returns {Promise<void>} promise
  6. */
  7. const runCommand = (command, args) => {
  8. const cp = require("child_process");
  9. return new Promise((resolve, reject) => {
  10. const executedCommand = cp.spawn(command, args, {
  11. stdio: "inherit",
  12. shell: true
  13. });
  14. executedCommand.on("error", error => {
  15. reject(error);
  16. });
  17. executedCommand.on("exit", code => {
  18. if (code === 0) {
  19. resolve();
  20. } else {
  21. reject();
  22. }
  23. });
  24. });
  25. };
  26. /**
  27. * @param {string} packageName name of the package
  28. * @returns {boolean} is the package installed?
  29. */
  30. const isInstalled = packageName => {
  31. if (process.versions.pnp) {
  32. return true;
  33. }
  34. const path = require("path");
  35. const fs = require("graceful-fs");
  36. let dir = __dirname;
  37. do {
  38. try {
  39. if (
  40. fs.statSync(path.join(dir, "node_modules", packageName)).isDirectory()
  41. ) {
  42. return true;
  43. }
  44. } catch (_error) {
  45. // Nothing
  46. }
  47. } while (dir !== (dir = path.dirname(dir)));
  48. // https://github.com/nodejs/node/blob/v18.9.1/lib/internal/modules/cjs/loader.js#L1274
  49. // eslint-disable-next-line no-warning-comments
  50. // @ts-ignore
  51. for (const internalPath of require("module").globalPaths) {
  52. try {
  53. if (fs.statSync(path.join(internalPath, packageName)).isDirectory()) {
  54. return true;
  55. }
  56. } catch (_error) {
  57. // Nothing
  58. }
  59. }
  60. return false;
  61. };
  62. /**
  63. * @param {CliOption} cli options
  64. * @returns {void}
  65. */
  66. const runCli = cli => {
  67. const path = require("path");
  68. const pkgPath = require.resolve(`${cli.package}/package.json`);
  69. const pkg = require(pkgPath);
  70. if (pkg.type === "module" || /\.mjs/i.test(pkg.bin[cli.binName])) {
  71. import(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName])).catch(
  72. error => {
  73. console.error(error);
  74. process.exitCode = 1;
  75. }
  76. );
  77. } else {
  78. require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]));
  79. }
  80. };
  81. /**
  82. * @typedef {object} CliOption
  83. * @property {string} name display name
  84. * @property {string} package npm package name
  85. * @property {string} binName name of the executable file
  86. * @property {boolean} installed currently installed?
  87. * @property {string} url homepage
  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. };
  97. if (!cli.installed) {
  98. const path = require("path");
  99. const fs = require("graceful-fs");
  100. const readLine = require("readline");
  101. const notify =
  102. "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} */ (packageManager),
  148. installOptions.concat(cli.package)
  149. )
  150. .then(() => {
  151. runCli(cli);
  152. })
  153. .catch(error => {
  154. console.error(error);
  155. process.exitCode = 1;
  156. });
  157. });
  158. } else {
  159. runCli(cli);
  160. }