webpack.js 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. // eslint-disable-next-line node/no-missing-require
  70. const pkg = require(pkgPath);
  71. if (pkg.type === "module" || /\.mjs/i.test(pkg.bin[cli.binName])) {
  72. // eslint-disable-next-line node/no-unsupported-features/es-syntax
  73. import(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName])).catch(
  74. error => {
  75. console.error(error);
  76. process.exitCode = 1;
  77. }
  78. );
  79. } else {
  80. // eslint-disable-next-line node/no-missing-require
  81. require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]));
  82. }
  83. };
  84. /**
  85. * @typedef {Object} CliOption
  86. * @property {string} name display name
  87. * @property {string} package npm package name
  88. * @property {string} binName name of the executable file
  89. * @property {boolean} installed currently installed?
  90. * @property {string} url homepage
  91. */
  92. /** @type {CliOption} */
  93. const cli = {
  94. name: "webpack-cli",
  95. package: "webpack-cli",
  96. binName: "webpack-cli",
  97. installed: isInstalled("webpack-cli"),
  98. url: "https://github.com/webpack/webpack-cli"
  99. };
  100. if (!cli.installed) {
  101. const path = require("path");
  102. const fs = require("graceful-fs");
  103. const readLine = require("readline");
  104. const notify =
  105. "CLI for webpack must be installed.\n" + ` ${cli.name} (${cli.url})\n`;
  106. console.error(notify);
  107. let packageManager;
  108. if (fs.existsSync(path.resolve(process.cwd(), "yarn.lock"))) {
  109. packageManager = "yarn";
  110. } else if (fs.existsSync(path.resolve(process.cwd(), "pnpm-lock.yaml"))) {
  111. packageManager = "pnpm";
  112. } else {
  113. packageManager = "npm";
  114. }
  115. const installOptions = [packageManager === "yarn" ? "add" : "install", "-D"];
  116. console.error(
  117. `We will use "${packageManager}" to install the CLI via "${packageManager} ${installOptions.join(
  118. " "
  119. )} ${cli.package}".`
  120. );
  121. const question = `Do you want to install 'webpack-cli' (yes/no): `;
  122. const questionInterface = readLine.createInterface({
  123. input: process.stdin,
  124. output: process.stderr
  125. });
  126. // In certain scenarios (e.g. when STDIN is not in terminal mode), the callback function will not be
  127. // executed. Setting the exit code here to ensure the script exits correctly in those cases. The callback
  128. // function is responsible for clearing the exit code if the user wishes to install webpack-cli.
  129. process.exitCode = 1;
  130. questionInterface.question(question, answer => {
  131. questionInterface.close();
  132. const normalizedAnswer = answer.toLowerCase().startsWith("y");
  133. if (!normalizedAnswer) {
  134. console.error(
  135. "You need to install 'webpack-cli' to use webpack via CLI.\n" +
  136. "You can also install the CLI manually."
  137. );
  138. return;
  139. }
  140. process.exitCode = 0;
  141. console.log(
  142. `Installing '${
  143. cli.package
  144. }' (running '${packageManager} ${installOptions.join(" ")} ${
  145. cli.package
  146. }')...`
  147. );
  148. runCommand(packageManager, installOptions.concat(cli.package))
  149. .then(() => {
  150. runCli(cli);
  151. })
  152. .catch(error => {
  153. console.error(error);
  154. process.exitCode = 1;
  155. });
  156. });
  157. } else {
  158. runCli(cli);
  159. }