@umijs/bundler-webpack 4.0.0-canary.20220429.3 → 4.0.0-canary.20220506.2

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,218 @@
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.getConfig = void 0;
7
+ const path_1 = require("path");
8
+ const webpack_1 = __importDefault(require("../../compiled/webpack"));
9
+ const webpack_5_chain_1 = __importDefault(require("../../compiled/webpack-5-chain"));
10
+ const constants_1 = require("../constants");
11
+ const RuntimePublicPathPlugin_1 = require("../plugins/RuntimePublicPathPlugin");
12
+ const types_1 = require("../types");
13
+ const browsersList_1 = require("../utils/browsersList");
14
+ const assetRules_1 = require("./assetRules");
15
+ const bundleAnalyzerPlugin_1 = require("./bundleAnalyzerPlugin");
16
+ const compressPlugin_1 = require("./compressPlugin");
17
+ const copyPlugin_1 = require("./copyPlugin");
18
+ const cssRules_1 = require("./cssRules");
19
+ const definePlugin_1 = require("./definePlugin");
20
+ const detectDeadCodePlugin_1 = require("./detectDeadCodePlugin");
21
+ const fastRefreshPlugin_1 = require("./fastRefreshPlugin");
22
+ const forkTSCheckerPlugin_1 = require("./forkTSCheckerPlugin");
23
+ const harmonyLinkingErrorPlugin_1 = require("./harmonyLinkingErrorPlugin");
24
+ const ignorePlugin_1 = require("./ignorePlugin");
25
+ const javaScriptRules_1 = require("./javaScriptRules");
26
+ const manifestPlugin_1 = require("./manifestPlugin");
27
+ const miniCSSExtractPlugin_1 = require("./miniCSSExtractPlugin");
28
+ const nodePolyfill_1 = require("./nodePolyfill");
29
+ const progressPlugin_1 = require("./progressPlugin");
30
+ const speedMeasureWebpackPlugin_1 = require("./speedMeasureWebpackPlugin");
31
+ const svgRules_1 = require("./svgRules");
32
+ async function getConfig(opts) {
33
+ const { userConfig } = opts;
34
+ const isDev = opts.env === types_1.Env.development;
35
+ const config = new webpack_5_chain_1.default();
36
+ userConfig.targets || (userConfig.targets = constants_1.DEFAULT_BROWSER_TARGETS);
37
+ const useHash = !!(opts.hash || (userConfig.hash && !isDev));
38
+ const applyOpts = {
39
+ name: opts.name,
40
+ config,
41
+ userConfig,
42
+ cwd: opts.cwd,
43
+ env: opts.env,
44
+ babelPreset: opts.babelPreset,
45
+ extraBabelPlugins: opts.extraBabelPlugins || [],
46
+ extraBabelPresets: opts.extraBabelPresets || [],
47
+ extraBabelIncludes: opts.extraBabelIncludes || [],
48
+ extraEsbuildLoaderHandler: opts.extraEsbuildLoaderHandler || [],
49
+ browsers: (0, browsersList_1.getBrowsersList)({
50
+ targets: userConfig.targets,
51
+ }),
52
+ useHash,
53
+ staticPathPrefix: opts.staticPathPrefix !== undefined ? opts.staticPathPrefix : 'static/',
54
+ };
55
+ // mode
56
+ config.mode(opts.env);
57
+ config.stats('none');
58
+ // entry
59
+ Object.keys(opts.entry).forEach((key) => {
60
+ const entry = config.entry(key);
61
+ if (isDev && opts.hmr) {
62
+ entry.add(require.resolve('../../client/client/client'));
63
+ }
64
+ entry.add(opts.entry[key]);
65
+ });
66
+ // devtool
67
+ config.devtool(isDev
68
+ ? userConfig.devtool === false
69
+ ? false
70
+ : userConfig.devtool || constants_1.DEFAULT_DEVTOOL
71
+ : userConfig.devtool);
72
+ // output
73
+ const absOutputPath = (0, path_1.join)(opts.cwd, userConfig.outputPath || constants_1.DEFAULT_OUTPUT_PATH);
74
+ const disableCompress = process.env.COMPRESS === 'none';
75
+ config.output
76
+ .path(absOutputPath)
77
+ .filename(useHash ? `[name].[contenthash:8].js` : `[name].js`)
78
+ .chunkFilename(useHash ? `[name].[contenthash:8].async.js` : `[name].js`)
79
+ .publicPath(userConfig.publicPath || 'auto')
80
+ .pathinfo(isDev || disableCompress);
81
+ // resolve
82
+ // prettier-ignore
83
+ config.resolve
84
+ .set('symlinks', true)
85
+ .modules
86
+ .add('node_modules')
87
+ .end()
88
+ .alias
89
+ .merge(userConfig.alias || {})
90
+ .end()
91
+ .extensions
92
+ .merge([
93
+ '.wasm',
94
+ '.mjs',
95
+ '.js',
96
+ '.jsx',
97
+ '.ts',
98
+ '.tsx',
99
+ '.json'
100
+ ])
101
+ .end();
102
+ // externals
103
+ config.externals(userConfig.externals || []);
104
+ // target
105
+ config.target(['web', 'es5']);
106
+ // experiments
107
+ config.experiments({
108
+ topLevelAwait: true,
109
+ outputModule: !!userConfig.esm,
110
+ });
111
+ // node polyfill
112
+ await (0, nodePolyfill_1.addNodePolyfill)(applyOpts);
113
+ // rules
114
+ await (0, javaScriptRules_1.addJavaScriptRules)(applyOpts);
115
+ await (0, cssRules_1.addCSSRules)(applyOpts);
116
+ await (0, assetRules_1.addAssetRules)(applyOpts);
117
+ await (0, svgRules_1.addSVGRules)(applyOpts);
118
+ // plugins
119
+ // mini-css-extract-plugin
120
+ await (0, miniCSSExtractPlugin_1.addMiniCSSExtractPlugin)(applyOpts);
121
+ // ignoreMomentLocale
122
+ await (0, ignorePlugin_1.addIgnorePlugin)(applyOpts);
123
+ // define
124
+ await (0, definePlugin_1.addDefinePlugin)(applyOpts);
125
+ // fast refresh
126
+ await (0, fastRefreshPlugin_1.addFastRefreshPlugin)(applyOpts);
127
+ // progress
128
+ await (0, progressPlugin_1.addProgressPlugin)(applyOpts);
129
+ // detect-dead-code-plugin
130
+ await (0, detectDeadCodePlugin_1.addDetectDeadCodePlugin)(applyOpts);
131
+ // fork-ts-checker
132
+ await (0, forkTSCheckerPlugin_1.addForkTSCheckerPlugin)(applyOpts);
133
+ // copy
134
+ await (0, copyPlugin_1.addCopyPlugin)(applyOpts);
135
+ // manifest
136
+ await (0, manifestPlugin_1.addManifestPlugin)(applyOpts);
137
+ // hmr
138
+ if (isDev && opts.hmr) {
139
+ config.plugin('hmr').use(webpack_1.default.HotModuleReplacementPlugin);
140
+ }
141
+ // compress
142
+ await (0, compressPlugin_1.addCompressPlugin)(applyOpts);
143
+ // purgecss
144
+ // await applyPurgeCSSWebpackPlugin(applyOpts);
145
+ // handle HarmonyLinkingError
146
+ await (0, harmonyLinkingErrorPlugin_1.addHarmonyLinkingErrorPlugin)(applyOpts);
147
+ // remove node: prefix
148
+ // disable for performance
149
+ // await addNodePrefixPlugin(applyOpts);
150
+ // runtimePublicPath
151
+ if (userConfig.runtimePublicPath) {
152
+ config.plugin('runtimePublicPath').use(RuntimePublicPathPlugin_1.RuntimePublicPathPlugin);
153
+ }
154
+ // cache
155
+ if (opts.cache) {
156
+ config.cache({
157
+ type: 'filesystem',
158
+ version: require('../../package.json').version,
159
+ buildDependencies: {
160
+ config: opts.cache.buildDependencies || [],
161
+ },
162
+ cacheDirectory: opts.cache.cacheDirectory ||
163
+ // 使用 rootDir 是在有 APP_ROOT 时,把 cache 目录放在根目录下
164
+ (0, path_1.join)(opts.rootDir || opts.cwd, 'node_modules', '.cache', 'bundler-webpack'),
165
+ });
166
+ // tnpm 安装依赖的情况 webpack 默认的 managedPaths 不生效
167
+ // 使用 immutablePaths 避免 node_modules 的内容被写入缓存
168
+ // tnpm 安装的依赖路径中同时包含包名和版本号,满足 immutablePaths 使用的条件
169
+ // ref: smallfish
170
+ if ( /*isTnpm*/require('@umijs/utils/package').__npminstall_done) {
171
+ config.snapshot({
172
+ immutablePaths: [
173
+ opts.cache.absNodeModulesPath ||
174
+ (0, path_1.join)(opts.rootDir || opts.cwd, 'node_modules'),
175
+ ],
176
+ });
177
+ }
178
+ config.infrastructureLogging({
179
+ level: 'error',
180
+ ...(process.env.WEBPACK_FS_CACHE_DEBUG
181
+ ? {
182
+ debug: /webpack\.cache/,
183
+ }
184
+ : {}),
185
+ });
186
+ }
187
+ // analyzer
188
+ if (opts.analyze) {
189
+ await (0, bundleAnalyzerPlugin_1.addBundleAnalyzerPlugin)(applyOpts);
190
+ }
191
+ // chain webpack
192
+ if (opts.chainWebpack) {
193
+ await opts.chainWebpack(config, {
194
+ env: opts.env,
195
+ webpack: webpack_1.default,
196
+ });
197
+ }
198
+ if (userConfig.chainWebpack) {
199
+ await userConfig.chainWebpack(config, {
200
+ env: opts.env,
201
+ webpack: webpack_1.default,
202
+ });
203
+ }
204
+ let webpackConfig = config.toConfig();
205
+ // speed measure
206
+ // TODO: mini-css-extract-plugin 报错
207
+ webpackConfig = await (0, speedMeasureWebpackPlugin_1.addSpeedMeasureWebpackPlugin)({
208
+ webpackConfig,
209
+ });
210
+ if (opts.modifyWebpackConfig) {
211
+ webpackConfig = await opts.modifyWebpackConfig(webpackConfig, {
212
+ env: opts.env,
213
+ webpack: webpack_1.default,
214
+ });
215
+ }
216
+ return webpackConfig;
217
+ }
218
+ exports.getConfig = getConfig;
@@ -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 addCopyPlugin(opts: IOpts): Promise<void>;
10
+ export {};
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addCopyPlugin = void 0;
4
+ const fs_1 = require("fs");
5
+ const path_1 = require("path");
6
+ async function addCopyPlugin(opts) {
7
+ const { config, userConfig, cwd } = opts;
8
+ const copyPatterns = [
9
+ (0, fs_1.existsSync)((0, path_1.join)(cwd, 'public')) && {
10
+ from: (0, path_1.join)(cwd, 'public'),
11
+ },
12
+ ...(userConfig.copy
13
+ ? userConfig.copy.map((item) => {
14
+ if (typeof item === 'string') {
15
+ return {
16
+ from: (0, path_1.join)(cwd, item),
17
+ to: item,
18
+ };
19
+ }
20
+ return {
21
+ // 相对于 process.cwd,所以这里需要使用绝对路径
22
+ from: (0, path_1.join)(cwd, item.from),
23
+ to: item.to,
24
+ };
25
+ })
26
+ : []),
27
+ ].filter(Boolean);
28
+ if (copyPatterns.length) {
29
+ config
30
+ .plugin('copy')
31
+ .use(require('@umijs/bundler-webpack/compiled/copy-webpack-plugin'), [
32
+ {
33
+ patterns: copyPatterns,
34
+ },
35
+ ]);
36
+ }
37
+ }
38
+ exports.addCopyPlugin = addCopyPlugin;
@@ -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
+ browsers: any;
9
+ }
10
+ export declare function addCSSRules(opts: IOpts): Promise<void>;
11
+ export {};
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addCSSRules = void 0;
4
+ async function addCSSRules(opts) {
5
+ const { config, userConfig } = opts;
6
+ const rulesConfig = [
7
+ { name: 'css', test: /\.css(\?.*)?$/ },
8
+ {
9
+ name: 'less',
10
+ test: /\.less(\?.*)?$/,
11
+ loader: require.resolve('@umijs/bundler-webpack/compiled/less-loader'),
12
+ loaderOptions: {
13
+ implementation: require.resolve('@umijs/bundler-utils/compiled/less'),
14
+ lessOptions: {
15
+ modifyVars: userConfig.theme,
16
+ javascriptEnabled: true,
17
+ ...userConfig.lessLoader,
18
+ },
19
+ },
20
+ },
21
+ {
22
+ name: 'sass',
23
+ test: /\.(sass|scss)(\?.*)?$/,
24
+ loader: require.resolve('@umijs/bundler-webpack/compiled/sass-loader'),
25
+ loaderOptions: userConfig.sassLoader || {},
26
+ },
27
+ ];
28
+ for (const { name, test, loader, loaderOptions } of rulesConfig) {
29
+ const rule = config.module.rule(name);
30
+ const nestRulesConfig = [
31
+ userConfig.autoCSSModules && {
32
+ rule: rule
33
+ .test(test)
34
+ .oneOf('css-modules')
35
+ .resourceQuery(/modules/),
36
+ isCSSModules: true,
37
+ },
38
+ {
39
+ rule: rule.test(test).oneOf('css').sideEffects(true),
40
+ isCSSModules: false,
41
+ },
42
+ ].filter(Boolean);
43
+ // @ts-ignore
44
+ for (const { rule, isCSSModules } of nestRulesConfig) {
45
+ if (userConfig.styleLoader) {
46
+ rule
47
+ .use('style-loader')
48
+ .loader(require.resolve('@umijs/bundler-webpack/compiled/style-loader'))
49
+ .options({ base: 0, esModule: true, ...userConfig.styleLoader });
50
+ }
51
+ else {
52
+ rule
53
+ .use('mini-css-extract-plugin')
54
+ .loader(require.resolve('@umijs/bundler-webpack/compiled/mini-css-extract-plugin/loader'))
55
+ .options({
56
+ publicPath: './',
57
+ emit: true,
58
+ esModule: true,
59
+ });
60
+ }
61
+ rule
62
+ .use('css-loader')
63
+ .loader(require.resolve('css-loader'))
64
+ .options({
65
+ importLoaders: 1,
66
+ esModule: true,
67
+ url: true,
68
+ import: true,
69
+ ...(isCSSModules
70
+ ? {
71
+ modules: {
72
+ localIdentName: '[local]___[hash:base64:5]',
73
+ ...userConfig.cssLoaderModules,
74
+ },
75
+ }
76
+ : {}),
77
+ ...userConfig.cssLoader,
78
+ });
79
+ rule
80
+ .use('postcss-loader')
81
+ .loader(require.resolve('@umijs/bundler-webpack/compiled/postcss-loader'))
82
+ .options({
83
+ postcssOptions: {
84
+ ident: 'postcss',
85
+ plugins: [
86
+ require('@umijs/bundler-webpack/compiled/postcss-flexbugs-fixes'),
87
+ require('postcss-preset-env')({
88
+ browsers: opts.browsers,
89
+ autoprefixer: {
90
+ flexbox: 'no-2009',
91
+ ...userConfig.autoprefixer,
92
+ },
93
+ stage: 3,
94
+ }),
95
+ ].concat(userConfig.extraPostCSSPlugins || []),
96
+ ...userConfig.postcssLoader,
97
+ },
98
+ });
99
+ if (loader) {
100
+ rule
101
+ .use(loader)
102
+ .loader(typeof loader === 'string' ? require.resolve(loader) : loader)
103
+ .options(loaderOptions || {});
104
+ }
105
+ }
106
+ }
107
+ }
108
+ exports.addCSSRules = addCSSRules;
@@ -0,0 +1,15 @@
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 resolveDefine(opts: {
10
+ define: any;
11
+ }): {
12
+ 'process.env': Record<string, any>;
13
+ };
14
+ export declare function addDefinePlugin(opts: IOpts): Promise<void>;
15
+ export {};
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addDefinePlugin = exports.resolveDefine = void 0;
4
+ const webpack_1 = require("@umijs/bundler-webpack/compiled/webpack");
5
+ const prefixRE = /^UMI_APP_/;
6
+ const ENV_SHOULD_PASS = ['NODE_ENV', 'HMR', 'SOCKET_SERVER', 'ERROR_OVERLAY'];
7
+ function resolveDefine(opts) {
8
+ const env = {};
9
+ Object.keys(process.env).forEach((key) => {
10
+ if (prefixRE.test(key) || ENV_SHOULD_PASS.includes(key)) {
11
+ env[key] = process.env[key];
12
+ }
13
+ });
14
+ for (const key in env) {
15
+ env[key] = JSON.stringify(env[key]);
16
+ }
17
+ const define = {};
18
+ if (opts.define) {
19
+ for (const key in opts.define) {
20
+ define[key] = JSON.stringify(opts.define[key]);
21
+ }
22
+ }
23
+ return {
24
+ 'process.env': env,
25
+ ...define,
26
+ };
27
+ }
28
+ exports.resolveDefine = resolveDefine;
29
+ async function addDefinePlugin(opts) {
30
+ const { config, userConfig } = opts;
31
+ config.plugin('define').use(webpack_1.DefinePlugin, [
32
+ resolveDefine({
33
+ define: userConfig.define || {},
34
+ }),
35
+ ]);
36
+ }
37
+ exports.addDefinePlugin = addDefinePlugin;
@@ -0,0 +1,12 @@
1
+ import { Compilation } from '@umijs/bundler-webpack/compiled/webpack';
2
+ import { DeadCodeParams } from '../types';
3
+ export interface Options extends DeadCodeParams {
4
+ patterns: string[];
5
+ exclude: string[];
6
+ failOnHint: boolean;
7
+ detectUnusedFiles: boolean;
8
+ detectUnusedExport: boolean;
9
+ }
10
+ export declare const disabledFolders: string[];
11
+ declare const detectDeadCode: (compilation: Compilation, options: Options) => void;
12
+ export default detectDeadCode;
@@ -0,0 +1,120 @@
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.disabledFolders = void 0;
7
+ const webpack_1 = require("@umijs/bundler-webpack/compiled/webpack");
8
+ const utils_1 = require("@umijs/utils");
9
+ const path_1 = __importDefault(require("path"));
10
+ exports.disabledFolders = [
11
+ 'node_modules',
12
+ '.umi',
13
+ '.umi-production',
14
+ 'dist',
15
+ ];
16
+ const detectDeadCode = (compilation, options) => {
17
+ const assets = getWebpackAssets(compilation);
18
+ const compiledFilesDictionary = convertFilesToDict(assets);
19
+ const includedFiles = getPattern(options)
20
+ .map((pattern) => utils_1.glob.sync(pattern))
21
+ .flat();
22
+ const unusedFiles = options.detectUnusedFiles
23
+ ? includedFiles.filter((file) => !compiledFilesDictionary[file])
24
+ : [];
25
+ const unusedExportMap = options.detectUnusedExport
26
+ ? getUnusedExportMap(convertFilesToDict(includedFiles), compilation)
27
+ : {};
28
+ logUnusedFiles(unusedFiles);
29
+ logUnusedExportMap(unusedExportMap);
30
+ const hasUnusedThings = unusedFiles.length || Object.keys(unusedExportMap).length;
31
+ if (hasUnusedThings && options.failOnHint) {
32
+ process.exit(2);
33
+ }
34
+ };
35
+ const getPattern = (options) => {
36
+ return options.patterns
37
+ .map((pattern) => path_1.default.resolve(options.context || '', pattern))
38
+ .concat(options.exclude.map((pattern) => path_1.default.resolve(options.context || '', `!${pattern}`)))
39
+ .map(convertToUnixPath);
40
+ };
41
+ const getUnusedExportMap = (includedFileMap, compilation) => {
42
+ const unusedExportMap = {};
43
+ compilation.chunks.forEach((chunk) => {
44
+ compilation.chunkGraph.getChunkModules(chunk).forEach((module) => {
45
+ outputUnusedExportMap(compilation, chunk, module, includedFileMap, unusedExportMap);
46
+ });
47
+ });
48
+ return unusedExportMap;
49
+ };
50
+ const outputUnusedExportMap = (compilation, chunk, module, includedFileMap, unusedExportMap) => {
51
+ if (!(module instanceof webpack_1.NormalModule) || !module.resource) {
52
+ return;
53
+ }
54
+ const path = convertToUnixPath(module.resource);
55
+ if (!/^((?!(node_modules)).)*$/.test(path))
56
+ return;
57
+ const providedExports = compilation.chunkGraph.moduleGraph.getProvidedExports(module);
58
+ const usedExports = compilation.chunkGraph.moduleGraph.getUsedExports(module, chunk.runtime);
59
+ if (usedExports !== true &&
60
+ providedExports !== true &&
61
+ includedFileMap[path]) {
62
+ if (usedExports === false) {
63
+ if (providedExports === null || providedExports === void 0 ? void 0 : providedExports.length) {
64
+ unusedExportMap[path] = providedExports;
65
+ }
66
+ }
67
+ else if (providedExports instanceof Array) {
68
+ const unusedExports = providedExports.filter((item) => usedExports && !usedExports.has(item));
69
+ if (unusedExports.length) {
70
+ unusedExportMap[path] = unusedExports;
71
+ }
72
+ }
73
+ }
74
+ };
75
+ const logUnusedExportMap = (unusedExportMap) => {
76
+ if (!Object.keys(unusedExportMap).length) {
77
+ return;
78
+ }
79
+ let numberOfUnusedExport = 0;
80
+ let logStr = '';
81
+ Object.keys(unusedExportMap).forEach((filePath, fileIndex) => {
82
+ const unusedExports = unusedExportMap[filePath];
83
+ logStr += [
84
+ `\n${fileIndex + 1}. `,
85
+ utils_1.chalk.yellow(`${filePath}\n`),
86
+ ' >>> ',
87
+ utils_1.chalk.yellow(`${unusedExports.join(', ')}`),
88
+ ].join('');
89
+ numberOfUnusedExport += unusedExports.length;
90
+ });
91
+ console.log(utils_1.chalk.yellow.bold('\nWarning:'), utils_1.chalk.yellow(`There are ${numberOfUnusedExport} unused exports in ${Object.keys(unusedExportMap).length} files:`), logStr, utils_1.chalk.red.bold('\nPlease be careful if you want to remove them (¬º-°)¬.\n'));
92
+ };
93
+ const getWebpackAssets = (compilation) => {
94
+ const outputPath = compilation.getPath(compilation.compiler.outputPath);
95
+ const assets = [
96
+ ...Array.from(compilation.fileDependencies),
97
+ ...compilation
98
+ .getAssets()
99
+ .map((asset) => path_1.default.join(outputPath, asset.name)),
100
+ ];
101
+ return assets;
102
+ };
103
+ const convertFilesToDict = (assets) => {
104
+ return assets
105
+ .filter((file) => Boolean(file) &&
106
+ exports.disabledFolders.every((disabledPath) => !file.includes(disabledPath)))
107
+ .reduce((fileDictionary, file) => {
108
+ const unixFile = convertToUnixPath(file);
109
+ fileDictionary[unixFile] = true;
110
+ return fileDictionary;
111
+ }, {});
112
+ };
113
+ const logUnusedFiles = (unusedFiles) => {
114
+ if (!(unusedFiles === null || unusedFiles === void 0 ? void 0 : unusedFiles.length)) {
115
+ return;
116
+ }
117
+ console.log(utils_1.chalk.yellow.bold('\nWarning:'), utils_1.chalk.yellow(`There are ${unusedFiles.length} unused files:`), ...unusedFiles.map((file, index) => `\n${index + 1}. ${utils_1.chalk.yellow(file)}`), utils_1.chalk.red.bold('\nPlease be careful if you want to remove them (¬º-°)¬.\n'));
118
+ };
119
+ const convertToUnixPath = (path) => path.replace(/\\+/g, '/');
120
+ exports.default = detectDeadCode;
@@ -0,0 +1,9 @@
1
+ import Config from '@umijs/bundler-webpack/compiled/webpack-5-chain';
2
+ import { Env, IConfig } from '../types';
3
+ interface IOpts {
4
+ userConfig: IConfig;
5
+ config: Config;
6
+ env: Env;
7
+ }
8
+ export declare function addDetectDeadCodePlugin(opts: IOpts): Promise<void>;
9
+ export {};
@@ -0,0 +1,70 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.addDetectDeadCodePlugin = void 0;
27
+ const types_1 = require("../types");
28
+ const detectDeadCode_1 = __importStar(require("./detectDeadCode"));
29
+ const defaultOptions = {
30
+ patterns: [`!(${detectDeadCode_1.disabledFolders.join('|')})/**/*.*`],
31
+ exclude: [],
32
+ failOnHint: false,
33
+ detectUnusedFiles: true,
34
+ detectUnusedExport: true,
35
+ };
36
+ class DetectDeadCodePlugin {
37
+ constructor(options) {
38
+ this.options = defaultOptions;
39
+ this.handleAfterEmit = (compilation, callback) => {
40
+ (0, detectDeadCode_1.default)(compilation, this.options);
41
+ callback();
42
+ };
43
+ if (!options) {
44
+ return;
45
+ }
46
+ this.options = {
47
+ ...this.options,
48
+ ...options,
49
+ };
50
+ }
51
+ apply(compiler) {
52
+ if (!this.options.context) {
53
+ this.options = {
54
+ ...this.options,
55
+ context: compiler.context,
56
+ };
57
+ }
58
+ compiler.hooks.afterEmit.tapAsync('DetectDeadCodePlugin', this.handleAfterEmit);
59
+ }
60
+ }
61
+ async function addDetectDeadCodePlugin(opts) {
62
+ const { config, userConfig } = opts;
63
+ const isDev = opts.env === types_1.Env.development;
64
+ if (userConfig.deadCode && !isDev) {
65
+ config
66
+ .plugin('detect-dead-code-plugin')
67
+ .use(DetectDeadCodePlugin, [userConfig.deadCode]);
68
+ }
69
+ }
70
+ exports.addDetectDeadCodePlugin = addDetectDeadCodePlugin;
@@ -0,0 +1,12 @@
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
+ browsers: any;
9
+ name?: string;
10
+ }
11
+ export declare function addFastRefreshPlugin(opts: IOpts): Promise<void>;
12
+ export {};