@umijs/bundler-webpack 4.0.0-canary.20220429.2 → 4.0.0-canary.20220506.1

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.
Files changed (97) hide show
  1. package/dist/build.d.ts +20 -0
  2. package/dist/build.js +64 -0
  3. package/dist/cli.d.ts +1 -0
  4. package/dist/cli.js +81 -0
  5. package/dist/client/client.d.ts +1 -0
  6. package/dist/client/client.js +245 -0
  7. package/dist/config/_sampleFeature.d.ts +10 -0
  8. package/dist/config/_sampleFeature.js +11 -0
  9. package/dist/config/assetRules.d.ts +11 -0
  10. package/dist/config/assetRules.js +50 -0
  11. package/dist/config/bundleAnalyzerPlugin.d.ts +10 -0
  12. package/dist/config/bundleAnalyzerPlugin.js +19 -0
  13. package/dist/config/compressPlugin.d.ts +10 -0
  14. package/dist/config/compressPlugin.js +83 -0
  15. package/dist/config/config.d.ts +27 -0
  16. package/dist/config/config.js +218 -0
  17. package/dist/config/copyPlugin.d.ts +10 -0
  18. package/dist/config/copyPlugin.js +38 -0
  19. package/dist/config/cssRules.d.ts +11 -0
  20. package/dist/config/cssRules.js +108 -0
  21. package/dist/config/definePlugin.d.ts +15 -0
  22. package/dist/config/definePlugin.js +37 -0
  23. package/dist/config/detectDeadCode.d.ts +12 -0
  24. package/dist/config/detectDeadCode.js +120 -0
  25. package/dist/config/detectDeadCodePlugin.d.ts +9 -0
  26. package/dist/config/detectDeadCodePlugin.js +70 -0
  27. package/dist/config/fastRefreshPlugin.d.ts +12 -0
  28. package/dist/config/fastRefreshPlugin.js +23 -0
  29. package/dist/config/forkTSCheckerPlugin.d.ts +11 -0
  30. package/dist/config/forkTSCheckerPlugin.js +23 -0
  31. package/dist/config/harmonyLinkingErrorPlugin.d.ts +6 -0
  32. package/dist/config/harmonyLinkingErrorPlugin.js +31 -0
  33. package/dist/config/ignorePlugin.d.ts +10 -0
  34. package/dist/config/ignorePlugin.js +16 -0
  35. package/dist/config/javaScriptRules.d.ts +16 -0
  36. package/dist/config/javaScriptRules.js +177 -0
  37. package/dist/config/manifestPlugin.d.ts +11 -0
  38. package/dist/config/manifestPlugin.js +17 -0
  39. package/dist/config/miniCSSExtractPlugin.d.ts +11 -0
  40. package/dist/config/miniCSSExtractPlugin.js +22 -0
  41. package/dist/config/nodePolyfill.d.ts +10 -0
  42. package/dist/config/nodePolyfill.js +28 -0
  43. package/dist/config/nodePrefixPlugin.d.ts +11 -0
  44. package/dist/config/nodePrefixPlugin.js +14 -0
  45. package/dist/config/progressPlugin.d.ts +11 -0
  46. package/dist/config/progressPlugin.js +16 -0
  47. package/dist/config/purgecssWebpackPlugin.d.ts +10 -0
  48. package/dist/config/purgecssWebpackPlugin.js +21 -0
  49. package/dist/config/speedMeasureWebpackPlugin.d.ts +6 -0
  50. package/dist/config/speedMeasureWebpackPlugin.js +23 -0
  51. package/dist/config/svgRules.d.ts +12 -0
  52. package/dist/config/svgRules.js +53 -0
  53. package/dist/constants.d.ts +15 -0
  54. package/dist/constants.js +24 -0
  55. package/dist/dev.d.ts +25 -0
  56. package/dist/dev.js +134 -0
  57. package/dist/index.d.ts +8 -0
  58. package/dist/index.js +20 -0
  59. package/dist/loader/svgr.d.ts +4 -0
  60. package/dist/loader/svgr.js +58 -0
  61. package/dist/loader/swc.d.ts +4 -0
  62. package/dist/loader/swc.js +74 -0
  63. package/dist/plugins/ESBuildCSSMinifyPlugin.d.ts +11 -0
  64. package/dist/plugins/ESBuildCSSMinifyPlugin.js +52 -0
  65. package/dist/plugins/ParcelCSSMinifyPlugin.d.ts +10 -0
  66. package/dist/plugins/ParcelCSSMinifyPlugin.js +73 -0
  67. package/dist/plugins/ProgressPlugin.d.ts +15 -0
  68. package/dist/plugins/ProgressPlugin.js +44 -0
  69. package/dist/plugins/RuntimePublicPathPlugin.d.ts +4 -0
  70. package/dist/plugins/RuntimePublicPathPlugin.js +20 -0
  71. package/dist/plugins/_SamplePlugin.d.ts +9 -0
  72. package/dist/plugins/_SamplePlugin.js +14 -0
  73. package/dist/requireHook.d.ts +1 -0
  74. package/dist/requireHook.js +31 -0
  75. package/dist/schema.d.ts +3 -0
  76. package/dist/schema.js +84 -0
  77. package/dist/server/server.d.ts +17 -0
  78. package/dist/server/server.js +193 -0
  79. package/dist/server/ws.d.ts +11 -0
  80. package/dist/server/ws.js +42 -0
  81. package/dist/swcPlugins/autoCSSModules.d.ts +13 -0
  82. package/dist/swcPlugins/autoCSSModules.js +34 -0
  83. package/dist/swcPlugins/changeImportFromString.d.ts +2 -0
  84. package/dist/swcPlugins/changeImportFromString.js +10 -0
  85. package/dist/swcPlugins/lockCoreJS.d.ts +6 -0
  86. package/dist/swcPlugins/lockCoreJS.js +24 -0
  87. package/dist/types.d.ts +119 -0
  88. package/dist/types.js +30 -0
  89. package/dist/utils/browsersList.d.ts +5 -0
  90. package/dist/utils/browsersList.js +10 -0
  91. package/dist/utils/depMatch.d.ts +6 -0
  92. package/dist/utils/depMatch.js +46 -0
  93. package/dist/utils/formatWebpackMessages.d.ts +12 -0
  94. package/dist/utils/formatWebpackMessages.js +100 -0
  95. package/dist/utils/getEsBuildTarget.d.ts +5 -0
  96. package/dist/utils/getEsBuildTarget.js +12 -0
  97. package/package.json +5 -5
@@ -0,0 +1,20 @@
1
+ import webpack from '../compiled/webpack';
2
+ import { IOpts as IConfigOpts } from './config/config';
3
+ import { IConfig } from './types';
4
+ declare type IOpts = {
5
+ cwd: string;
6
+ rootDir?: string;
7
+ entry: Record<string, string>;
8
+ config: IConfig;
9
+ onBuildComplete?: Function;
10
+ babelPreset?: any;
11
+ chainWebpack?: Function;
12
+ modifyWebpackConfig?: Function;
13
+ beforeBabelPlugins?: any[];
14
+ beforeBabelPresets?: any[];
15
+ extraBabelPlugins?: any[];
16
+ extraBabelPresets?: any[];
17
+ clean?: boolean;
18
+ } & Pick<IConfigOpts, 'cache'>;
19
+ export declare function build(opts: IOpts): Promise<webpack.Stats>;
20
+ export {};
package/dist/build.js ADDED
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.build = void 0;
7
+ const utils_1 = require("@umijs/utils");
8
+ const webpack_1 = __importDefault(require("../compiled/webpack"));
9
+ const config_1 = require("./config/config");
10
+ const types_1 = require("./types");
11
+ async function build(opts) {
12
+ const webpackConfig = await (0, config_1.getConfig)({
13
+ cwd: opts.cwd,
14
+ rootDir: opts.rootDir,
15
+ env: types_1.Env.production,
16
+ entry: opts.entry,
17
+ userConfig: opts.config,
18
+ analyze: process.env.ANALYZE,
19
+ babelPreset: opts.babelPreset,
20
+ extraBabelPlugins: [
21
+ ...(opts.beforeBabelPlugins || []),
22
+ ...(opts.extraBabelPlugins || []),
23
+ ],
24
+ extraBabelPresets: [
25
+ ...(opts.beforeBabelPresets || []),
26
+ ...(opts.extraBabelPresets || []),
27
+ ],
28
+ extraBabelIncludes: opts.config.extraBabelIncludes,
29
+ chainWebpack: opts.chainWebpack,
30
+ modifyWebpackConfig: opts.modifyWebpackConfig,
31
+ cache: opts.cache,
32
+ });
33
+ let isFirstCompile = true;
34
+ return new Promise((resolve, reject) => {
35
+ utils_1.rimraf.sync(webpackConfig.output.path);
36
+ const compiler = (0, webpack_1.default)(webpackConfig);
37
+ compiler.run((err, stats) => {
38
+ var _a;
39
+ (_a = opts.onBuildComplete) === null || _a === void 0 ? void 0 : _a.call(opts, {
40
+ err,
41
+ stats,
42
+ isFirstCompile,
43
+ time: stats ? stats.endTime - stats.startTime : null,
44
+ });
45
+ isFirstCompile = false;
46
+ if (err || (stats === null || stats === void 0 ? void 0 : stats.hasErrors())) {
47
+ if (err) {
48
+ // console.error(err);
49
+ reject(err);
50
+ }
51
+ if (stats) {
52
+ const errorMsg = stats.toString('errors-only');
53
+ // console.error(errorMsg);
54
+ reject(new Error(errorMsg));
55
+ }
56
+ }
57
+ else {
58
+ resolve(stats);
59
+ }
60
+ compiler.close(() => { });
61
+ });
62
+ });
63
+ }
64
+ exports.build = build;
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const esbuild_1 = __importDefault(require("@umijs/bundler-utils/compiled/esbuild"));
7
+ const utils_1 = require("@umijs/utils");
8
+ const assert_1 = __importDefault(require("assert"));
9
+ const fs_1 = require("fs");
10
+ const path_1 = require("path");
11
+ const build_1 = require("./build");
12
+ const dev_1 = require("./dev");
13
+ const args = (0, utils_1.yParser)(process.argv.slice(2), {});
14
+ const command = args._[0];
15
+ const cwd = process.cwd();
16
+ const entry = (0, utils_1.tryPaths)([
17
+ (0, path_1.join)(cwd, 'src/index.tsx'),
18
+ (0, path_1.join)(cwd, 'src/index.ts'),
19
+ (0, path_1.join)(cwd, 'index.tsx'),
20
+ (0, path_1.join)(cwd, 'index.ts'),
21
+ ]);
22
+ let config = {};
23
+ const configFile = (0, path_1.join)(cwd, args.config || 'config.ts');
24
+ utils_1.register.register({
25
+ implementor: esbuild_1.default,
26
+ });
27
+ utils_1.register.clearFiles();
28
+ if ((0, fs_1.existsSync)(configFile)) {
29
+ require('./requireHook');
30
+ config = require(configFile).default;
31
+ }
32
+ Object.assign(config, args);
33
+ if (command === 'build') {
34
+ (async () => {
35
+ process.env.NODE_ENV = 'production';
36
+ (0, assert_1.default)(entry, `Build failed: entry not found.`);
37
+ try {
38
+ await (0, build_1.build)({
39
+ config,
40
+ cwd,
41
+ entry: {
42
+ [getEntryKey(entry)]: entry,
43
+ },
44
+ });
45
+ }
46
+ catch (e) {
47
+ console.error(e);
48
+ }
49
+ })();
50
+ }
51
+ else if (command === 'dev') {
52
+ (async () => {
53
+ process.env.NODE_ENV = 'development';
54
+ try {
55
+ (0, assert_1.default)(entry, `Build failed: entry not found.`);
56
+ await (0, dev_1.dev)({
57
+ config,
58
+ cwd,
59
+ port: process.env.PORT,
60
+ entry: {
61
+ [getEntryKey(entry)]: entry,
62
+ },
63
+ cache: {
64
+ buildDependencies: [].filter(Boolean),
65
+ },
66
+ });
67
+ }
68
+ catch (e) {
69
+ console.error(e);
70
+ }
71
+ })();
72
+ }
73
+ else {
74
+ error(`Unsupported command ${command}.`);
75
+ }
76
+ function error(msg) {
77
+ console.error(utils_1.chalk.red(msg));
78
+ }
79
+ function getEntryKey(path) {
80
+ return (0, path_1.basename)(path, (0, path_1.extname)(path));
81
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,245 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ const strip_ansi_1 = __importDefault(require("@umijs/utils/compiled/strip-ansi"));
30
+ // @ts-ignore
31
+ const ErrorOverlay = __importStar(require("react-error-overlay"));
32
+ const constants_1 = require("../constants");
33
+ const formatWebpackMessages_1 = require("../utils/formatWebpackMessages");
34
+ console.log('[webpack] connecting...');
35
+ function getHost() {
36
+ if (process.env.SOCKET_SERVER) {
37
+ return new URL(process.env.SOCKET_SERVER);
38
+ }
39
+ return location;
40
+ }
41
+ function getSocketUrl() {
42
+ let h = getHost();
43
+ const host = h.host;
44
+ const isHttps = h.protocol === 'https:';
45
+ return `${isHttps ? 'wss' : 'ws'}://${host}`;
46
+ }
47
+ function getPingUrl() {
48
+ const h = getHost();
49
+ return `${h.protocol}//${h.host}/__umi_ping`;
50
+ }
51
+ let pingTimer = null;
52
+ let isFirstCompilation = true;
53
+ let mostRecentCompilationHash = null;
54
+ let hasCompileErrors = false;
55
+ let hadRuntimeError = false;
56
+ const pingUrl = getPingUrl();
57
+ const socket = new WebSocket(getSocketUrl(), 'webpack-hmr');
58
+ socket.addEventListener('message', async ({ data }) => {
59
+ data = JSON.parse(data);
60
+ if (data.type === 'connected') {
61
+ console.log(`[webpack] connected.`);
62
+ // proxy(nginx, docker) hmr ws maybe caused timeout,
63
+ // so send ping package let ws keep alive.
64
+ pingTimer = setInterval(() => socket.send('ping'), 30000);
65
+ }
66
+ else {
67
+ handleMessage(data).catch(console.error);
68
+ }
69
+ });
70
+ async function waitForSuccessfulPing(ms = 1000) {
71
+ // eslint-disable-next-line no-constant-condition
72
+ while (true) {
73
+ try {
74
+ await fetch(pingUrl);
75
+ break;
76
+ }
77
+ catch (e) {
78
+ await new Promise((resolve) => setTimeout(resolve, ms));
79
+ }
80
+ }
81
+ }
82
+ socket.addEventListener('close', async () => {
83
+ if (pingTimer)
84
+ clearInterval(pingTimer);
85
+ console.info('[webpack] Dev server disconnected. Polling for restart...');
86
+ await waitForSuccessfulPing();
87
+ location.reload();
88
+ });
89
+ ErrorOverlay.startReportingRuntimeErrors({
90
+ onError: function () {
91
+ hadRuntimeError = true;
92
+ },
93
+ filename: '/static/js/bundle.js',
94
+ });
95
+ // @ts-ignore
96
+ if (module.hot && typeof module.hot.dispose === 'function') {
97
+ // @ts-ignore
98
+ module.hot.dispose(function () {
99
+ // TODO: why do we need this?
100
+ ErrorOverlay.stopReportingRuntimeErrors();
101
+ });
102
+ }
103
+ // There is a newer version of the code available.
104
+ function handleAvailableHash(hash) {
105
+ // Update last known compilation hash.
106
+ mostRecentCompilationHash = hash;
107
+ }
108
+ function handleSuccess() {
109
+ const isHotUpdate = !isFirstCompilation;
110
+ isFirstCompilation = false;
111
+ hasCompileErrors = false;
112
+ // Attempt to apply hot updates or reload.
113
+ if (isHotUpdate) {
114
+ tryApplyUpdates(function onHotUpdateSuccess() {
115
+ // Only dismiss it when we're sure it's a hot update.
116
+ // Otherwise it would flicker right before the reload.
117
+ tryDismissErrorOverlay();
118
+ });
119
+ }
120
+ }
121
+ function handleWarnings(warnings) {
122
+ const isHotUpdate = !isFirstCompilation;
123
+ isFirstCompilation = false;
124
+ hasCompileErrors = false;
125
+ const formatted = (0, formatWebpackMessages_1.formatWebpackMessages)({
126
+ warnings,
127
+ errors: [],
128
+ });
129
+ // print warnings
130
+ if (typeof console !== 'undefined' && typeof console.warn === 'function') {
131
+ for (let i = 0; i < formatted.warnings.length; i++) {
132
+ if (i === 5) {
133
+ console.warn('There were more warnings in other files.\n' +
134
+ 'You can find a complete log in the terminal.');
135
+ break;
136
+ }
137
+ console.warn((0, strip_ansi_1.default)(formatted.warnings[i]));
138
+ }
139
+ }
140
+ // Attempt to apply hot updates or reload.
141
+ if (isHotUpdate) {
142
+ tryApplyUpdates(function onSuccessfulHotUpdate() {
143
+ // Only dismiss it when we're sure it's a hot update.
144
+ // Otherwise it would flicker right before the reload.
145
+ tryDismissErrorOverlay();
146
+ });
147
+ }
148
+ }
149
+ function handleErrors(errors) {
150
+ isFirstCompilation = false;
151
+ hasCompileErrors = true;
152
+ const formatted = (0, formatWebpackMessages_1.formatWebpackMessages)({
153
+ warnings: [],
154
+ errors,
155
+ });
156
+ // Only show the first error.
157
+ ErrorOverlay.reportBuildError(formatted.errors[0]);
158
+ // Also log them to the console.
159
+ if (typeof console !== 'undefined' && typeof console.error === 'function') {
160
+ for (let i = 0; i < formatted.errors.length; i++) {
161
+ console.error((0, strip_ansi_1.default)(formatted.errors[i]));
162
+ }
163
+ }
164
+ }
165
+ function tryDismissErrorOverlay() {
166
+ if (!hasCompileErrors) {
167
+ ErrorOverlay.dismissBuildError();
168
+ }
169
+ }
170
+ // Is there a newer version of this code available?
171
+ function isUpdateAvailable() {
172
+ // @ts-ignore
173
+ return mostRecentCompilationHash !== __webpack_hash__;
174
+ }
175
+ function canApplyUpdates() {
176
+ // @ts-ignore
177
+ return module.hot.status() === 'idle';
178
+ }
179
+ function canAcceptErrors() {
180
+ // NOTE: This var is injected by Webpack's DefinePlugin, and is a boolean instead of string.
181
+ const hasReactRefresh = process.env.FAST_REFRESH;
182
+ // @ts-ignore
183
+ const status = module.hot.status();
184
+ // React refresh can handle hot-reloading over errors.
185
+ // However, when hot-reload status is abort or fail,
186
+ // it indicates the current update cannot be applied safely,
187
+ // and thus we should bail out to a forced reload for consistency.
188
+ return hasReactRefresh && ['abort', 'fail'].indexOf(status) === -1;
189
+ }
190
+ function tryApplyUpdates(onHotUpdateSuccess) {
191
+ // @ts-ignore
192
+ if (!module.hot) {
193
+ window.location.reload();
194
+ return;
195
+ }
196
+ if (!isUpdateAvailable() || !canApplyUpdates()) {
197
+ return;
198
+ }
199
+ function handleApplyUpdates(err, updatedModules) {
200
+ const haveErrors = err || hadRuntimeError;
201
+ // When there is no error but updatedModules is unavailable,
202
+ // it indicates a critical failure in hot-reloading,
203
+ // e.g. server is not ready to serve new bundle,
204
+ // and hence we need to do a forced reload.
205
+ const needsForcedReload = !err && !updatedModules;
206
+ if ((haveErrors && !canAcceptErrors()) || needsForcedReload) {
207
+ window.location.reload();
208
+ }
209
+ if (onHotUpdateSuccess)
210
+ onHotUpdateSuccess();
211
+ // While we were updating, there was a new update! Do it again.
212
+ if (isUpdateAvailable()) {
213
+ tryApplyUpdates();
214
+ }
215
+ }
216
+ // @ts-ignore
217
+ module.hot
218
+ .check(/* autoApply */ true)
219
+ .then((updatedModules) => {
220
+ handleApplyUpdates(null, updatedModules);
221
+ })
222
+ .catch((err) => {
223
+ handleApplyUpdates(err, null);
224
+ });
225
+ }
226
+ async function handleMessage(payload) {
227
+ // console.log('[payload]', payload);
228
+ switch (payload.type) {
229
+ case constants_1.MESSAGE_TYPE.hash:
230
+ handleAvailableHash(payload.data);
231
+ break;
232
+ case constants_1.MESSAGE_TYPE.stillOk:
233
+ case constants_1.MESSAGE_TYPE.ok:
234
+ handleSuccess();
235
+ break;
236
+ case constants_1.MESSAGE_TYPE.errors:
237
+ handleErrors(payload.data);
238
+ break;
239
+ case constants_1.MESSAGE_TYPE.warnings:
240
+ handleWarnings(payload.data);
241
+ break;
242
+ default:
243
+ // Do nothing
244
+ }
245
+ }
@@ -0,0 +1,10 @@
1
+ import Config from '@umijs/bundler-webpack/compiled/webpack-5-chain';
2
+ import { Env, IConfig } from '../types';
3
+ interface IOpts {
4
+ config: Config;
5
+ userConfig: IConfig;
6
+ cwd: string;
7
+ env: Env;
8
+ }
9
+ export declare function addSampleFeature(opts: IOpts): Promise<void>;
10
+ export {};
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addSampleFeature = void 0;
4
+ async function addSampleFeature(opts) {
5
+ const { config, userConfig, cwd, env } = opts;
6
+ config;
7
+ userConfig;
8
+ cwd;
9
+ env;
10
+ }
11
+ exports.addSampleFeature = addSampleFeature;
@@ -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
+ config: Config;
5
+ userConfig: IConfig;
6
+ cwd: string;
7
+ env: Env;
8
+ staticPathPrefix: string;
9
+ }
10
+ export declare function addAssetRules(opts: IOpts): Promise<void>;
11
+ export {};
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addAssetRules = void 0;
4
+ async function addAssetRules(opts) {
5
+ const { config, userConfig } = opts;
6
+ const inlineLimit = parseInt(userConfig.inlineLimit || '10000', 10);
7
+ const rule = config.module.rule('asset');
8
+ rule
9
+ .oneOf('avif')
10
+ .test(/\.avif$/)
11
+ .type('asset')
12
+ .mimetype('image/avif')
13
+ .parser({
14
+ dataUrlCondition: {
15
+ maxSize: inlineLimit,
16
+ },
17
+ })
18
+ .generator({
19
+ filename: `${opts.staticPathPrefix}[name].[hash:8].[ext]`,
20
+ });
21
+ rule
22
+ .oneOf('image')
23
+ .test(/\.(bmp|gif|jpg|jpeg|png)$/)
24
+ .type('asset')
25
+ .parser({
26
+ dataUrlCondition: {
27
+ maxSize: inlineLimit,
28
+ },
29
+ })
30
+ .generator({
31
+ filename: `${opts.staticPathPrefix}[name].[hash:8].[ext]`,
32
+ });
33
+ const fallback = rule
34
+ .oneOf('fallback')
35
+ .exclude.add(/^$/) /* handle data: resources */
36
+ .add(/\.(js|mjs|jsx|ts|tsx)$/)
37
+ .add(/\.(css|less|sass|scss|stylus)$/)
38
+ .add(/\.html$/)
39
+ .add(/\.json$/);
40
+ if (userConfig.mdx) {
41
+ fallback.add(/\.mdx?$/);
42
+ }
43
+ fallback
44
+ .end()
45
+ .type('asset/resource')
46
+ .generator({
47
+ filename: `${opts.staticPathPrefix}[name].[hash:8].[ext]`,
48
+ });
49
+ }
50
+ exports.addAssetRules = addAssetRules;
@@ -0,0 +1,10 @@
1
+ import Config from '@umijs/bundler-webpack/compiled/webpack-5-chain';
2
+ import { Env, IConfig } from '../types';
3
+ interface IOpts {
4
+ config: Config;
5
+ userConfig: IConfig;
6
+ cwd: string;
7
+ env: Env;
8
+ }
9
+ export declare function addBundleAnalyzerPlugin(opts: IOpts): Promise<void>;
10
+ export {};
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addBundleAnalyzerPlugin = void 0;
4
+ // @ts-ignore
5
+ const webpack_bundle_analyzer_1 = require("@umijs/bundler-webpack/compiled/webpack-bundle-analyzer");
6
+ async function addBundleAnalyzerPlugin(opts) {
7
+ const { config } = opts;
8
+ config.plugin('webpack-bundle-analyzer').use(webpack_bundle_analyzer_1.BundleAnalyzerPlugin, [
9
+ // https://github.com/webpack-contrib/webpack-bundle-analyzer
10
+ {
11
+ analyzerMode: 'server',
12
+ analyzerPort: process.env.ANALYZE_PORT || 8888,
13
+ openAnalyzer: false,
14
+ logLevel: 'info',
15
+ defaultSizes: 'parsed',
16
+ },
17
+ ]);
18
+ }
19
+ exports.addBundleAnalyzerPlugin = addBundleAnalyzerPlugin;
@@ -0,0 +1,10 @@
1
+ import Config from '../../compiled/webpack-5-chain';
2
+ import { Env, IConfig } from '../types';
3
+ interface IOpts {
4
+ config: Config;
5
+ userConfig: IConfig;
6
+ cwd: string;
7
+ env: Env;
8
+ }
9
+ export declare function addCompressPlugin(opts: IOpts): Promise<void>;
10
+ export {};
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.addCompressPlugin = void 0;
7
+ // @ts-ignore
8
+ const css_minimizer_webpack_plugin_1 = __importDefault(require("@umijs/bundler-webpack/compiled/css-minimizer-webpack-plugin"));
9
+ const terser_webpack_plugin_1 = __importDefault(require("../../compiled/terser-webpack-plugin"));
10
+ const ESBuildCSSMinifyPlugin_1 = __importDefault(require("../plugins/ESBuildCSSMinifyPlugin"));
11
+ const ParcelCSSMinifyPlugin_1 = require("../plugins/ParcelCSSMinifyPlugin");
12
+ const types_1 = require("../types");
13
+ const getEsBuildTarget_1 = require("../utils/getEsBuildTarget");
14
+ async function addCompressPlugin(opts) {
15
+ const { config, userConfig, env } = opts;
16
+ const jsMinifier = userConfig.jsMinifier || types_1.JSMinifier.esbuild;
17
+ const cssMinifier = userConfig.cssMinifier || types_1.CSSMinifier.esbuild;
18
+ if (env === types_1.Env.development ||
19
+ process.env.COMPRESS === 'none' ||
20
+ (jsMinifier === types_1.JSMinifier.none && cssMinifier === types_1.CSSMinifier.none)) {
21
+ config.optimization.minimize(false);
22
+ return;
23
+ }
24
+ config.optimization.minimize(true);
25
+ let minify;
26
+ let terserOptions;
27
+ if (jsMinifier === types_1.JSMinifier.esbuild) {
28
+ minify = terser_webpack_plugin_1.default.esbuildMinify;
29
+ terserOptions = {
30
+ target: (0, getEsBuildTarget_1.getEsBuildTarget)({
31
+ targets: userConfig.targets || {},
32
+ }),
33
+ };
34
+ }
35
+ else if (jsMinifier === types_1.JSMinifier.terser) {
36
+ minify = terser_webpack_plugin_1.default.terserMinify;
37
+ }
38
+ else if (jsMinifier === types_1.JSMinifier.swc) {
39
+ minify = terser_webpack_plugin_1.default.swcMinify;
40
+ }
41
+ else if (jsMinifier === types_1.JSMinifier.uglifyJs) {
42
+ minify = terser_webpack_plugin_1.default.uglifyJsMinify;
43
+ }
44
+ else if (jsMinifier !== types_1.JSMinifier.none) {
45
+ throw new Error(`Unsupported jsMinifier ${userConfig.jsMinifier}.`);
46
+ }
47
+ terserOptions = {
48
+ ...terserOptions,
49
+ ...userConfig.jsMinifierOptions,
50
+ };
51
+ if (jsMinifier !== types_1.JSMinifier.none) {
52
+ config.optimization.minimizer(`js-${jsMinifier}`).use(terser_webpack_plugin_1.default, [
53
+ {
54
+ minify,
55
+ terserOptions,
56
+ },
57
+ ]);
58
+ }
59
+ if (cssMinifier === types_1.CSSMinifier.esbuild) {
60
+ config.optimization
61
+ .minimizer(`css-${cssMinifier}`)
62
+ .use(ESBuildCSSMinifyPlugin_1.default, [userConfig.cssMinifierOptions]);
63
+ }
64
+ else if (cssMinifier === types_1.CSSMinifier.cssnano) {
65
+ config.optimization
66
+ .minimizer(`css-${cssMinifier}`)
67
+ .use(css_minimizer_webpack_plugin_1.default, [
68
+ {
69
+ minimizerOptions: userConfig.cssMinifierOptions,
70
+ parallel: true,
71
+ },
72
+ ]);
73
+ }
74
+ else if (cssMinifier === types_1.CSSMinifier.parcelCSS) {
75
+ config.optimization
76
+ .minimizer(`css-${cssMinifier}`)
77
+ .use(ParcelCSSMinifyPlugin_1.ParcelCSSMinifyPlugin);
78
+ }
79
+ else if (cssMinifier !== types_1.CSSMinifier.none) {
80
+ throw new Error(`Unsupported cssMinifier ${userConfig.cssMinifier}.`);
81
+ }
82
+ }
83
+ exports.addCompressPlugin = addCompressPlugin;
@@ -0,0 +1,27 @@
1
+ import { Configuration } from '../../compiled/webpack';
2
+ import { Env, IConfig } from '../types';
3
+ export interface IOpts {
4
+ cwd: string;
5
+ rootDir?: string;
6
+ env: Env;
7
+ entry: Record<string, string>;
8
+ extraBabelPresets?: any[];
9
+ extraBabelPlugins?: any[];
10
+ extraBabelIncludes?: string[];
11
+ extraEsbuildLoaderHandler?: any[];
12
+ babelPreset?: any;
13
+ chainWebpack?: Function;
14
+ modifyWebpackConfig?: Function;
15
+ hash?: boolean;
16
+ hmr?: boolean;
17
+ staticPathPrefix?: string;
18
+ userConfig: IConfig;
19
+ analyze?: any;
20
+ name?: string;
21
+ cache?: {
22
+ absNodeModulesPath?: string;
23
+ buildDependencies?: string[];
24
+ cacheDirectory?: string;
25
+ };
26
+ }
27
+ export declare function getConfig(opts: IOpts): Promise<Configuration>;