UNPKG

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