@umijs/bundler-webpack 4.0.0-canary.20220325.1 → 4.0.0-rc.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,34 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
1
10
  import stripAnsi from '@umijs/utils/compiled/strip-ansi';
2
11
  // @ts-ignore
3
12
  import * as ErrorOverlay from 'react-error-overlay';
4
13
  import { MESSAGE_TYPE } from '../constants';
5
14
  import { formatWebpackMessages } from '../utils/formatWebpackMessages';
6
15
  console.log('[webpack] connecting...');
16
+ function getSocketHost() {
17
+ let l = location;
18
+ if (process.env.SOCKET_SERVER) {
19
+ l = new URL(process.env.SOCKET_SERVER);
20
+ }
21
+ const host = l.host;
22
+ const isHttps = l.protocol === 'https:';
23
+ return `${isHttps ? 'wss' : 'ws'}://${host}`;
24
+ }
7
25
  let pingTimer = null;
8
- const host = location.host;
9
- const wsUrl = `ws://${host}`;
10
26
  let isFirstCompilation = true;
11
27
  let mostRecentCompilationHash = null;
12
28
  let hasCompileErrors = false;
13
29
  let hadRuntimeError = false;
14
- const socket = new WebSocket(wsUrl, 'webpack-hmr');
15
- socket.addEventListener('message', async ({ data }) => {
30
+ const socket = new WebSocket(getSocketHost(), 'webpack-hmr');
31
+ socket.addEventListener('message', ({ data }) => __awaiter(void 0, void 0, void 0, function* () {
16
32
  data = JSON.parse(data);
17
33
  if (data.type === 'connected') {
18
34
  console.log(`[webpack] connected.`);
@@ -23,26 +39,28 @@ socket.addEventListener('message', async ({ data }) => {
23
39
  else {
24
40
  handleMessage(data).catch(console.error);
25
41
  }
26
- });
27
- async function waitForSuccessfulPing(ms = 1000) {
28
- // eslint-disable-next-line no-constant-condition
29
- while (true) {
30
- try {
31
- await fetch(`/__umi_ping`);
32
- break;
33
- }
34
- catch (e) {
35
- await new Promise((resolve) => setTimeout(resolve, ms));
42
+ }));
43
+ function waitForSuccessfulPing(ms = 1000) {
44
+ return __awaiter(this, void 0, void 0, function* () {
45
+ // eslint-disable-next-line no-constant-condition
46
+ while (true) {
47
+ try {
48
+ yield fetch(`/__umi_ping`);
49
+ break;
50
+ }
51
+ catch (e) {
52
+ yield new Promise((resolve) => setTimeout(resolve, ms));
53
+ }
36
54
  }
37
- }
55
+ });
38
56
  }
39
- socket.addEventListener('close', async () => {
57
+ socket.addEventListener('close', () => __awaiter(void 0, void 0, void 0, function* () {
40
58
  if (pingTimer)
41
59
  clearInterval(pingTimer);
42
60
  console.info('[webpack] Dev server disconnected. Polling for restart...');
43
- await waitForSuccessfulPing();
61
+ yield waitForSuccessfulPing();
44
62
  location.reload();
45
- });
63
+ }));
46
64
  ErrorOverlay.startReportingRuntimeErrors({
47
65
  onError: function () {
48
66
  hadRuntimeError = true;
@@ -180,23 +198,25 @@ function tryApplyUpdates(onHotUpdateSuccess) {
180
198
  handleApplyUpdates(err, null);
181
199
  });
182
200
  }
183
- async function handleMessage(payload) {
184
- // console.log('[payload]', payload);
185
- switch (payload.type) {
186
- case MESSAGE_TYPE.hash:
187
- handleAvailableHash(payload.data);
188
- break;
189
- case MESSAGE_TYPE.stillOk:
190
- case MESSAGE_TYPE.ok:
191
- handleSuccess();
192
- break;
193
- case MESSAGE_TYPE.errors:
194
- handleErrors(payload.data);
195
- break;
196
- case MESSAGE_TYPE.warnings:
197
- handleWarnings(payload.data);
198
- break;
199
- default:
200
- // Do nothing
201
- }
201
+ function handleMessage(payload) {
202
+ return __awaiter(this, void 0, void 0, function* () {
203
+ // console.log('[payload]', payload);
204
+ switch (payload.type) {
205
+ case MESSAGE_TYPE.hash:
206
+ handleAvailableHash(payload.data);
207
+ break;
208
+ case MESSAGE_TYPE.stillOk:
209
+ case MESSAGE_TYPE.ok:
210
+ handleSuccess();
211
+ break;
212
+ case MESSAGE_TYPE.errors:
213
+ handleErrors(payload.data);
214
+ break;
215
+ case MESSAGE_TYPE.warnings:
216
+ handleWarnings(payload.data);
217
+ break;
218
+ default:
219
+ // Do nothing
220
+ }
221
+ });
202
222
  }
@@ -10,3 +10,6 @@ export var MESSAGE_TYPE;
10
10
  MESSAGE_TYPE["stillOk"] = "still-ok";
11
11
  MESSAGE_TYPE["invalid"] = "invalid";
12
12
  })(MESSAGE_TYPE || (MESSAGE_TYPE = {}));
13
+ export const DEFAULT_BROWSER_TARGETS = {
14
+ chrome: 80,
15
+ };
@@ -41,14 +41,21 @@ const ErrorOverlay = __importStar(require("react-error-overlay"));
41
41
  const constants_1 = require("../constants");
42
42
  const formatWebpackMessages_1 = require("../utils/formatWebpackMessages");
43
43
  console.log('[webpack] connecting...');
44
+ function getSocketHost() {
45
+ let l = location;
46
+ if (process.env.SOCKET_SERVER) {
47
+ l = new URL(process.env.SOCKET_SERVER);
48
+ }
49
+ const host = l.host;
50
+ const isHttps = l.protocol === 'https:';
51
+ return `${isHttps ? 'wss' : 'ws'}://${host}`;
52
+ }
44
53
  let pingTimer = null;
45
- const host = location.host;
46
- const wsUrl = `ws://${host}`;
47
54
  let isFirstCompilation = true;
48
55
  let mostRecentCompilationHash = null;
49
56
  let hasCompileErrors = false;
50
57
  let hadRuntimeError = false;
51
- const socket = new WebSocket(wsUrl, 'webpack-hmr');
58
+ const socket = new WebSocket(getSocketHost(), 'webpack-hmr');
52
59
  socket.addEventListener('message', ({ data }) => __awaiter(void 0, void 0, void 0, function* () {
53
60
  data = JSON.parse(data);
54
61
  if (data.type === 'connected') {
@@ -35,6 +35,7 @@ const javaScriptRules_1 = require("./javaScriptRules");
35
35
  const manifestPlugin_1 = require("./manifestPlugin");
36
36
  const miniCSSExtractPlugin_1 = require("./miniCSSExtractPlugin");
37
37
  const nodePolyfill_1 = require("./nodePolyfill");
38
+ const nodePrefixPlugin_1 = require("./nodePrefixPlugin");
38
39
  const progressPlugin_1 = require("./progressPlugin");
39
40
  const speedMeasureWebpackPlugin_1 = require("./speedMeasureWebpackPlugin");
40
41
  const svgRules_1 = require("./svgRules");
@@ -153,6 +154,8 @@ function getConfig(opts) {
153
154
  // await applyPurgeCSSWebpackPlugin(applyOpts);
154
155
  // handle HarmonyLinkingError
155
156
  yield (0, harmonyLinkingErrorPlugin_1.addHarmonyLinkingErrorPlugin)(applyOpts);
157
+ // remove node: prefix
158
+ yield (0, nodePrefixPlugin_1.addNodePrefixPlugin)(applyOpts);
156
159
  // runtimePublicPath
157
160
  if (userConfig.runtimePublicPath) {
158
161
  config.plugin('runtimePublicPath').use(RuntimePublicPathPlugin_1.RuntimePublicPathPlugin);
@@ -14,12 +14,12 @@ const webpack_1 = require("@umijs/bundler-webpack/compiled/webpack");
14
14
  function addNodePolyfill(opts) {
15
15
  return __awaiter(this, void 0, void 0, function* () {
16
16
  const { config } = opts;
17
- const nodeLibs = require('node-libs-browser');
18
17
  config.plugin('node-polyfill-provider').use(webpack_1.ProvidePlugin, [
19
18
  {
20
19
  Buffer: ['buffer', 'Buffer'],
21
20
  },
22
21
  ]);
22
+ const nodeLibs = require('node-libs-browser');
23
23
  config.resolve.fallback.merge(Object.assign(Object.assign({}, Object.keys(nodeLibs).reduce((memo, key) => {
24
24
  if (nodeLibs[key]) {
25
25
  memo[key] = nodeLibs[key];
@@ -0,0 +1,11 @@
1
+ import Config from '@umijs/bundler-webpack/compiled/webpack-5-chain';
2
+ import { Env, IConfig } from '../types';
3
+ interface IOpts {
4
+ name?: string;
5
+ config: Config;
6
+ userConfig: IConfig;
7
+ cwd: string;
8
+ env: Env;
9
+ }
10
+ export declare function addNodePrefixPlugin(opts: IOpts): Promise<void>;
11
+ export {};
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.addNodePrefixPlugin = void 0;
13
+ const webpack_1 = require("@umijs/bundler-webpack/compiled/webpack");
14
+ function addNodePrefixPlugin(opts) {
15
+ return __awaiter(this, void 0, void 0, function* () {
16
+ const { config } = opts;
17
+ config.plugin('node-prefix-plugin').use(webpack_1.NormalModuleReplacementPlugin, [
18
+ /^node:/,
19
+ (resource) => {
20
+ resource.request = resource.request.replace(/^node:/, '');
21
+ },
22
+ ]);
23
+ });
24
+ }
25
+ exports.addNodePrefixPlugin = addNodePrefixPlugin;
package/dist/dev.js CHANGED
@@ -46,6 +46,11 @@ function dev(opts) {
46
46
  return {
47
47
  version: require('../package.json').version,
48
48
  esbuildMode: !!((_a = opts.config.mfsu) === null || _a === void 0 ? void 0 : _a.esbuild),
49
+ alias: opts.config.alias,
50
+ externals: opts.config.externals,
51
+ theme: opts.config.theme,
52
+ runtimePublicPath: opts.config.runtimePublicPath,
53
+ publicPath: opts.config.publicPath,
49
54
  };
50
55
  },
51
56
  });
package/dist/schema.js CHANGED
@@ -46,6 +46,7 @@ function getSchemas() {
46
46
  fastRefresh: (Joi) => Joi.boolean(),
47
47
  forkTSChecker: (Joi) => Joi.object(),
48
48
  hash: (Joi) => Joi.boolean(),
49
+ https: (Joi) => Joi.object(),
49
50
  ignoreMomentLocale: (Joi) => Joi.boolean(),
50
51
  inlineLimit: (Joi) => Joi.number(),
51
52
  jsMinifier: (Joi) => Joi.string().valid(types_1.JSMinifier.esbuild, types_1.JSMinifier.swc, types_1.JSMinifier.terser, types_1.JSMinifier.uglifyJs, types_1.JSMinifier.none),
@@ -0,0 +1,5 @@
1
+ /// <reference types="node" />
2
+ import { RequestListener } from 'http';
3
+ import https from 'https';
4
+ import { HttpsParams } from '../types';
5
+ export declare function createHttpsServer(app: RequestListener, httpsConfig: HttpsParams): Promise<https.Server>;
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.createHttpsServer = void 0;
16
+ const utils_1 = require("@umijs/utils");
17
+ const fs_1 = require("fs");
18
+ const https_1 = __importDefault(require("https"));
19
+ const path_1 = require("path");
20
+ const defaultHttpsHosts = ['localhost', '127.0.0.1'];
21
+ function createHttpsServer(app, httpsConfig) {
22
+ return __awaiter(this, void 0, void 0, function* () {
23
+ utils_1.logger.wait('[HTTPS] Starting service in https mode...');
24
+ // Check if mkcert is installed
25
+ try {
26
+ yield utils_1.execa.execa('mkcert', ['--version']);
27
+ }
28
+ catch (e) {
29
+ utils_1.logger.error('[HTTPS] The mkcert has not been installed.');
30
+ utils_1.logger.info('[HTTPS] Please follow the guide to install manually.');
31
+ switch (process.platform) {
32
+ case 'darwin':
33
+ console.log(utils_1.chalk.green('$ brew install mkcert'));
34
+ console.log(utils_1.chalk.gray('# If you use firefox, please install nss.'));
35
+ console.log(utils_1.chalk.green('$ brew install nss'));
36
+ console.log(utils_1.chalk.green('$ mkcert -install'));
37
+ break;
38
+ case 'win32':
39
+ console.log(utils_1.chalk.green('Checkout https://github.com/FiloSottile/mkcert#windows'));
40
+ break;
41
+ case 'linux':
42
+ console.log(utils_1.chalk.green('Checkout https://github.com/FiloSottile/mkcert#linux'));
43
+ break;
44
+ default:
45
+ break;
46
+ }
47
+ throw new Error(`[HTTPS] mkcert not found.`);
48
+ }
49
+ let { key, cert, hosts } = httpsConfig;
50
+ hosts = hosts || defaultHttpsHosts;
51
+ if (!key || !cert) {
52
+ key = (0, path_1.join)(__dirname, 'umi.key.pem');
53
+ cert = (0, path_1.join)(__dirname, 'umi.pem');
54
+ }
55
+ // Generate cert and key files if they are not exist.
56
+ if (!(0, fs_1.existsSync)(key) || !(0, fs_1.existsSync)(cert)) {
57
+ utils_1.logger.wait('[HTTPS] Generating cert and key files...');
58
+ yield utils_1.execa.execa('mkcert', [
59
+ '-cert-file',
60
+ cert,
61
+ '-key-file',
62
+ key,
63
+ ...hosts,
64
+ ]);
65
+ }
66
+ // Create server
67
+ return https_1.default.createServer({
68
+ key: (0, fs_1.readFileSync)(key, 'utf-8'),
69
+ cert: (0, fs_1.readFileSync)(cert, 'utf-8'),
70
+ }, app);
71
+ });
72
+ }
73
+ exports.createHttpsServer = createHttpsServer;
@@ -12,5 +12,5 @@ interface IOpts {
12
12
  afterMiddlewares?: any[];
13
13
  onDevCompileDone?: Function;
14
14
  }
15
- export declare function createServer(opts: IOpts): Promise<http.Server>;
15
+ export declare function createServer(opts: IOpts): Promise<import("https").Server | http.Server | null>;
16
16
  export {};
@@ -21,6 +21,7 @@ const fs_1 = require("fs");
21
21
  const http_1 = __importDefault(require("http"));
22
22
  const path_1 = require("path");
23
23
  const constants_1 = require("../constants");
24
+ const https_1 = require("./https");
24
25
  const ws_1 = require("./ws");
25
26
  function createServer(opts) {
26
27
  return __awaiter(this, void 0, void 0, function* () {
@@ -65,7 +66,7 @@ function createServer(opts) {
65
66
  const compiler = (0, webpack_1.default)(Array.isArray(webpackConfig) ? webpackConfig : [webpackConfig]);
66
67
  const webpackDevMiddleware = require('@umijs/bundler-webpack/compiled/webpack-dev-middleware');
67
68
  const compilerMiddleware = webpackDevMiddleware(compiler, {
68
- publicPath: '/',
69
+ publicPath: userConfig.publicPath || '/',
69
70
  writeToDisk: userConfig.writeToDisk,
70
71
  stats: 'none',
71
72
  // watchOptions: { ignored }
@@ -171,17 +172,23 @@ function createServer(opts) {
171
172
  next();
172
173
  }
173
174
  });
174
- const server = http_1.default.createServer(app);
175
+ const server = userConfig.https
176
+ ? yield (0, https_1.createHttpsServer)(app, userConfig.https)
177
+ : http_1.default.createServer(app);
178
+ if (!server) {
179
+ return null;
180
+ }
175
181
  const ws = (0, ws_1.createWebSocketServer)(server);
176
182
  ws.wss.on('connection', (socket) => {
177
183
  if (stats) {
178
184
  sendStats(getStats(stats), false, socket);
179
185
  }
180
186
  });
187
+ const protocol = userConfig.https ? 'https:' : 'http:';
181
188
  const port = opts.port || 8000;
182
189
  server.listen(port, () => {
183
190
  const host = opts.host && opts.host !== '0.0.0.0' ? opts.host : '127.0.0.1';
184
- utils_1.logger.ready(`App listening at ${utils_1.chalk.green(`http://${host}:${port}`)}`);
191
+ utils_1.logger.ready(`App listening at ${utils_1.chalk.green(`${protocol}//${host}:${port}`)}`);
185
192
  });
186
193
  return server;
187
194
  });
@@ -1,7 +1,8 @@
1
1
  /// <reference types="node" />
2
- import { Server } from 'http';
2
+ import { Server as HttpServer } from 'http';
3
+ import { Server as HttpsServer } from 'https';
3
4
  import WebSocket from '../../compiled/ws';
4
- export declare function createWebSocketServer(server: Server): {
5
+ export declare function createWebSocketServer(server: HttpServer | HttpsServer): {
5
6
  send(message: string): void;
6
7
  wss: WebSocket.Server;
7
8
  close(): void;
package/dist/types.d.ts CHANGED
@@ -41,6 +41,11 @@ export interface DeadCodeParams {
41
41
  detectUnusedExport?: boolean;
42
42
  context?: string;
43
43
  }
44
+ export interface HttpsParams {
45
+ key?: string;
46
+ cert?: string;
47
+ hosts?: string[];
48
+ }
44
49
  export interface IConfig {
45
50
  alias?: Record<string, string>;
46
51
  autoCSSModules?: boolean;
@@ -63,6 +68,7 @@ export interface IConfig {
63
68
  depTranspiler?: Transpiler;
64
69
  devtool?: Config.DevTool;
65
70
  deadCode?: DeadCodeParams;
71
+ https?: HttpsParams;
66
72
  externals?: WebpackConfig['externals'];
67
73
  esm?: {
68
74
  [key: string]: any;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umijs/bundler-webpack",
3
- "version": "4.0.0-canary.20220325.1",
3
+ "version": "4.0.0-rc.11",
4
4
  "description": "@umijs/bundler-webpack",
5
5
  "homepage": "https://github.com/umijs/umi-next/tree/master/packages/bundler-webpack#readme",
6
6
  "bugs": "https://github.com/umijs/umi-next/issues",
@@ -35,9 +35,10 @@
35
35
  "@svgr/plugin-jsx": "^6.2.1",
36
36
  "@svgr/plugin-svgo": "^6.2.0",
37
37
  "@types/hapi__joi": "17.1.8",
38
- "@umijs/babel-preset-umi": "4.0.0-canary.20220325.1",
39
- "@umijs/mfsu": "4.0.0-canary.20220325.1",
40
- "@umijs/utils": "4.0.0-canary.20220325.1",
38
+ "@umijs/babel-preset-umi": "4.0.0-rc.11",
39
+ "@umijs/bundler-utils": "4.0.0-rc.11",
40
+ "@umijs/mfsu": "4.0.0-rc.11",
41
+ "@umijs/utils": "4.0.0-rc.11",
41
42
  "css-loader": "6.7.1",
42
43
  "es5-imcompatible-versions": "^0.1.73",
43
44
  "jest-worker": "27.5.1",