webpack.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. // eslint-disable-next-line n/no-unsupported-features/es-syntax
  72. import(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName])).catch(
  73. error => {
  74. console.error(error);
  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 =
  103. "CLI for webpack must be installed.\n" + ` ${cli.name} (${cli.url})\n`;
  104. console.error(notify);
  105. /** @type {string | undefined} */
  106. let packageManager;
  107. if (fs.existsSync(path.resolve(process.cwd(), "yarn.lock"))) {
  108. packageManager = "yarn";
  109. } else if (fs.existsSync(path.resolve(process.cwd(), "pnpm-lock.yaml"))) {
  110. packageManager = "pnpm";
  111. } else {
  112. packageManager = "npm";
  113. }
  114. const installOptions = [packageManager === "yarn" ? "add" : "install", "-D"];
  115. console.error(
  116. `We will use "${packageManager}" to install the CLI via "${packageManager} ${installOptions.join(
  117. " "
  118. )} ${cli.package}".`
  119. );
  120. const question = `Do you want to install 'webpack-cli' (yes/no): `;
  121. const questionInterface = readLine.createInterface({
  122. input: process.stdin,
  123. output: process.stderr
  124. });
  125. // In certain scenarios (e.g. when STDIN is not in terminal mode), the callback function will not be
  126. // executed. Setting the exit code here to ensure the script exits correctly in those cases. The callback
  127. // function is responsible for clearing the exit code if the user wishes to install webpack-cli.
  128. process.exitCode = 1;
  129. questionInterface.question(question, answer => {
  130. questionInterface.close();
  131. const normalizedAnswer = answer.toLowerCase().startsWith("y");
  132. if (!normalizedAnswer) {
  133. console.error(
  134. "You need to install 'webpack-cli' to use webpack via CLI.\n" +
  135. "You can also install the CLI manually."
  136. );
  137. return;
  138. }
  139. process.exitCode = 0;
  140. console.log(
  141. `Installing '${
  142. cli.package
  143. }' (running '${packageManager} ${installOptions.join(" ")} ${
  144. cli.package
  145. }')...`
  146. );
  147. runCommand(
  148. /** @type {string} */ (packageManager),
  149. installOptions.concat(cli.package)
  150. )
  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. }