Skip to content

Commit 4f5b166

Browse files
authored
refactor(helpers): avoid importing helpers via barrel files (#6309)
1 parent 94a84cc commit 4f5b166

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+274
-296
lines changed

e2e/cases/hmr/reconnect/index.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { expect, rspackTest } from '@e2e/helper';
55
const cwd = __dirname;
66

77
rspackTest(
8-
'should reconnect Web Socket server as expected',
8+
'should reconnect WebSocket server as expected',
99
async ({ page, dev, devOnly, editFile }) => {
1010
await fs.promises.cp(join(cwd, 'src'), join(cwd, 'test-temp-src'), {
1111
recursive: true,

packages/core/src/cli/init.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import path from 'node:path';
22
import { createRsbuild } from '../createRsbuild';
3-
import { castArray, ensureAbsolutePath } from '../helpers';
3+
import { castArray } from '../helpers';
4+
import { ensureAbsolutePath } from '../helpers/path';
45
import { loadConfig as baseLoadConfig } from '../loadConfig';
56
import { logger } from '../logger';
67
import { watchFilesForRestart } from '../restart';

packages/core/src/createRsbuild.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@ import {
55
castArray,
66
color,
77
getNodeEnv,
8-
isEmptyDir,
98
isFunction,
109
pick,
1110
setNodeEnv,
1211
} from './helpers';
12+
import { isEmptyDir } from './helpers/fs';
1313
import { initPluginAPI } from './initPlugins';
1414
import { type LoadEnvResult, loadEnv } from './loadEnv';
1515
import { isDebug, logger } from './logger';

packages/core/src/defaultConfig.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ import {
1919
TS_CONFIG_FILE,
2020
WASM_DIST_DIR,
2121
} from './constants';
22-
import { findExists, getNodeEnv, isFileExists } from './helpers';
22+
import { getNodeEnv } from './helpers';
23+
import { findExists, isFileExists } from './helpers/fs';
2324
import { mergeRsbuildConfig } from './mergeConfig';
2425
import type {
2526
NormalizedConfig,
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { DEFAULT_ASSET_PREFIX } from '../constants';
2+
import type { Rspack } from '../types';
3+
4+
export const isMultiCompiler = (
5+
compiler: Rspack.Compiler | Rspack.MultiCompiler,
6+
): compiler is Rspack.MultiCompiler => {
7+
return 'compilers' in compiler && Array.isArray(compiler.compilers);
8+
};
9+
10+
export const getPublicPathFromCompiler = (
11+
compiler: Rspack.Compiler | Rspack.Compilation,
12+
): string => {
13+
const { publicPath } = compiler.options.output;
14+
15+
if (typeof publicPath === 'string') {
16+
// 'auto' is a magic value in Rspack and behave like `publicPath: ""`
17+
if (publicPath === 'auto') {
18+
return '';
19+
}
20+
return publicPath.endsWith('/') ? publicPath : `${publicPath}/`;
21+
}
22+
23+
// publicPath function is not supported yet, fallback to default value
24+
return DEFAULT_ASSET_PREFIX;
25+
};
26+
27+
export const applyToCompiler = (
28+
compiler: Rspack.Compiler | Rspack.MultiCompiler,
29+
apply: (c: Rspack.Compiler, index: number) => void,
30+
): void => {
31+
if (isMultiCompiler(compiler)) {
32+
compiler.compilers.forEach(apply);
33+
} else {
34+
apply(compiler, 0);
35+
}
36+
};
37+
38+
export const addCompilationError = (
39+
compilation: Rspack.Compilation,
40+
message: string,
41+
): void => {
42+
compilation.errors.push(
43+
new compilation.compiler.webpack.WebpackError(message),
44+
);
45+
};

packages/core/src/helpers/index.ts

Lines changed: 1 addition & 184 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
1-
import { posix } from 'node:path';
2-
import { URL } from 'node:url';
31
import deepmerge from 'deepmerge';
42
import RspackChain from '../../compiled/rspack-chain';
5-
import { DEFAULT_ASSET_PREFIX } from '../constants';
63
import type {
74
FilenameConfig,
85
NormalizedConfig,
@@ -12,14 +9,7 @@ import type {
129
} from '../types';
1310
import { color } from './vendors';
1411

15-
export * from './fs';
16-
export * from './path';
17-
export * from './stats';
18-
export * from './vendors';
19-
export { RspackChain };
20-
21-
// Lazy compilation was stabilized in Rspack v1.5.0
22-
export const rspackMinVersion = '1.5.0';
12+
export { color, RspackChain };
2313

2414
export const getNodeEnv = (): string => process.env.NODE_ENV || '';
2515
export const setNodeEnv = (env: string): void => {
@@ -59,149 +49,6 @@ export const cloneDeep = <T>(value: T): T => {
5949
});
6050
};
6151

62-
const compareSemver = (version1: string, version2: string) => {
63-
const parts1 = version1.split('.').map(Number);
64-
const parts2 = version2.split('.').map(Number);
65-
const len = Math.max(parts1.length, parts2.length);
66-
67-
for (let i = 0; i < len; i++) {
68-
const item1 = parts1[i] ?? 0;
69-
const item2 = parts2[i] ?? 0;
70-
if (item1 > item2) {
71-
return 1;
72-
}
73-
if (item1 < item2) {
74-
return -1;
75-
}
76-
}
77-
78-
return 0;
79-
};
80-
81-
/**
82-
* If the application overrides the Rspack version to a lower one,
83-
* we should check that the Rspack version is greater than the minimum
84-
* supported version.
85-
*/
86-
export const isSatisfyRspackVersion = (originalVersion: string): boolean => {
87-
let version = originalVersion;
88-
89-
// The nightly version of Rspack is to append `-canary-abc` to the current version
90-
if (version.includes('-canary')) {
91-
version = version.split('-canary')[0];
92-
}
93-
94-
if (version && /^[\d.]+$/.test(version)) {
95-
return compareSemver(version, rspackMinVersion) >= 0;
96-
}
97-
98-
// ignore other unstable versions
99-
return true;
100-
};
101-
102-
export const removeLeadingSlash = (s: string): string => s.replace(/^\/+/, '');
103-
export const removeTailingSlash = (s: string): string => s.replace(/\/+$/, '');
104-
export const addTrailingSlash = (s: string): string =>
105-
s.endsWith('/') ? s : `${s}/`;
106-
107-
export const formatPublicPath = (
108-
publicPath: string,
109-
withSlash = true,
110-
): string => {
111-
// 'auto' is a magic value in Rspack and we should not add trailing slash
112-
if (publicPath === 'auto') {
113-
return publicPath;
114-
}
115-
116-
return withSlash
117-
? addTrailingSlash(publicPath)
118-
: removeTailingSlash(publicPath);
119-
};
120-
121-
export const getPublicPathFromChain = (
122-
chain: RspackChain,
123-
withSlash = true,
124-
): string => {
125-
const publicPath: Rspack.PublicPath = chain.output.get('publicPath');
126-
127-
if (typeof publicPath === 'string') {
128-
return formatPublicPath(publicPath, withSlash);
129-
}
130-
131-
return formatPublicPath(DEFAULT_ASSET_PREFIX, withSlash);
132-
};
133-
134-
export const getPublicPathFromCompiler = (
135-
compiler: Rspack.Compiler | Rspack.Compilation,
136-
): string => {
137-
const { publicPath } = compiler.options.output;
138-
139-
if (typeof publicPath === 'string') {
140-
// 'auto' is a magic value in Rspack and behave like `publicPath: ""`
141-
if (publicPath === 'auto') {
142-
return '';
143-
}
144-
return publicPath.endsWith('/') ? publicPath : `${publicPath}/`;
145-
}
146-
147-
// publicPath function is not supported yet, fallback to default value
148-
return DEFAULT_ASSET_PREFIX;
149-
};
150-
151-
export const urlJoin = (base: string, path: string) => {
152-
const [urlProtocol, baseUrl] = base.split('://');
153-
return `${urlProtocol}://${posix.join(baseUrl, path)}`;
154-
};
155-
156-
// Can be replaced with URL.canParse when we drop support for Node.js 18
157-
export const canParse = (url: string): boolean => {
158-
try {
159-
new URL(url);
160-
return true;
161-
} catch {
162-
return false;
163-
}
164-
};
165-
166-
export const ensureAssetPrefix = (
167-
url: string,
168-
assetPrefix: Rspack.PublicPath = DEFAULT_ASSET_PREFIX,
169-
): string => {
170-
// The use of an absolute URL without a protocol is technically legal,
171-
// however it cannot be parsed as a URL instance, just return it.
172-
// e.g. str is //example.com/foo.js
173-
if (url.startsWith('//')) {
174-
return url;
175-
}
176-
177-
// If str is an complete URL, just return it.
178-
// Only absolute url with hostname & protocol can be parsed into URL instance.
179-
// e.g. str is https://example.com/foo.js
180-
if (canParse(url)) {
181-
return url;
182-
}
183-
184-
// 'auto' is a magic value in Rspack and behave like `publicPath: ""`
185-
if (assetPrefix === 'auto') {
186-
return url;
187-
}
188-
189-
// function is not supported by this helper
190-
if (typeof assetPrefix === 'function') {
191-
return url;
192-
}
193-
194-
if (assetPrefix.startsWith('http')) {
195-
return urlJoin(assetPrefix, url);
196-
}
197-
198-
if (assetPrefix.startsWith('//')) {
199-
return urlJoin(`https:${assetPrefix}`, url).replace('https:', '');
200-
}
201-
202-
return posix.join(assetPrefix, url);
203-
};
204-
20552
export function getFilename(
20653
config: NormalizedConfig | NormalizedEnvironmentConfig,
20754
type: 'js',
@@ -299,24 +146,9 @@ export function partition<T>(
299146
return [truthy, falsy];
300147
}
301148

302-
export const applyToCompiler = (
303-
compiler: Rspack.Compiler | Rspack.MultiCompiler,
304-
apply: (c: Rspack.Compiler, index: number) => void,
305-
): void => {
306-
if (isMultiCompiler(compiler)) {
307-
compiler.compilers.forEach(apply);
308-
} else {
309-
apply(compiler, 0);
310-
}
311-
};
312-
313149
export const upperFirst = (str: string): string =>
314150
str ? str.charAt(0).toUpperCase() + str.slice(1) : '';
315151

316-
// Determine if the string is a URL
317-
export const isURL = (str: string): boolean =>
318-
str.startsWith('http') || str.startsWith('//:');
319-
320152
export const createVirtualModule = (content: string) =>
321153
`data:text/javascript,${content}`;
322154

@@ -325,12 +157,6 @@ export function isWebTarget(target: RsbuildTarget | RsbuildTarget[]): boolean {
325157
return targets.includes('web') || targets.includes('web-worker');
326158
}
327159

328-
export const isMultiCompiler = (
329-
compiler: Rspack.Compiler | Rspack.MultiCompiler,
330-
): compiler is Rspack.MultiCompiler => {
331-
return 'compilers' in compiler && Array.isArray(compiler.compilers);
332-
};
333-
334160
export function pick<T, U extends keyof T>(
335161
obj: T,
336162
keys: readonly U[],
@@ -384,15 +210,6 @@ export const isTTY = (type: 'stdin' | 'stdout' = 'stdout'): boolean => {
384210
);
385211
};
386212

387-
export const addCompilationError = (
388-
compilation: Rspack.Compilation,
389-
message: string,
390-
): void => {
391-
compilation.errors.push(
392-
new compilation.compiler.webpack.WebpackError(message),
393-
);
394-
};
395-
396213
export async function hash(data: string): Promise<string> {
397214
const crypto = await import('node:crypto');
398215
// Available in Node.js v20.12.0

packages/core/src/helpers/stats.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { logger } from '../logger';
22
import type { ActionType, RsbuildStats, Rspack } from '../types';
3-
import { isMultiCompiler } from './';
3+
import { isMultiCompiler } from './compiler';
44
import { formatStatsError } from './format';
55
import { color } from './vendors';
66

0 commit comments

Comments
 (0)