Skip to content

Commit 2114930

Browse files
committed
chore: rebase
1 parent a823737 commit 2114930

File tree

27 files changed

+335
-116
lines changed

27 files changed

+335
-116
lines changed

packages/core/src/config.ts

Lines changed: 46 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -983,7 +983,8 @@ const composeBundlelessExternalConfig = (
983983
} => {
984984
if (bundle) return { config: {} };
985985

986-
const isStyleRedirected = redirect.style ?? true;
986+
const styleRedirectPath = redirect.style?.path ?? true;
987+
const styleRedirectExtension = redirect.style?.extension ?? true;
987988
const jsRedirectPath = redirect.js?.path ?? true;
988989
const jsRedirectExtension = redirect.js?.extension ?? true;
989990

@@ -1002,60 +1003,70 @@ const composeBundlelessExternalConfig = (
10021003
if (!request || !getResolve || !context || !contextInfo) {
10031004
return callback();
10041005
}
1006+
const { issuer } = contextInfo;
10051007

10061008
if (!resolver) {
10071009
resolver = (await getResolve()) as RspackResolver;
10081010
}
10091011

1012+
async function redirectPath(request: string): Promise<string | undefined> {
1013+
try {
1014+
let resolvedRequest = request;
1015+
// use resolver to resolve the request
1016+
resolvedRequest = await resolver!(context!, resolvedRequest);
1017+
1018+
// only handle the request that is not in node_modules
1019+
if (!resolvedRequest.includes('node_modules')) {
1020+
resolvedRequest = normalizeSlash(
1021+
path.relative(path.dirname(issuer), resolvedRequest),
1022+
);
1023+
// Requests that fall through here cannot be matched by any other externals config ahead.
1024+
// Treat all these requests as relative import of source code. Node.js won't add the
1025+
// leading './' to the relative path resolved by `path.relative`. So add manually it here.
1026+
if (resolvedRequest[0] !== '.') {
1027+
resolvedRequest = `./${resolvedRequest}`;
1028+
}
1029+
return resolvedRequest;
1030+
}
1031+
// NOTE: If request is a phantom dependency, which means it can be resolved but not specified in dependencies or peerDependencies in package.json, the output will be incorrect to use when the package is published
1032+
// return the original request instead of the resolved request
1033+
return undefined;
1034+
} catch (e) {
1035+
// catch error when request can not be resolved by resolver
1036+
// e.g. A react component library importing and using 'react' but while not defining
1037+
// it in devDependencies and peerDependencies. Preserve 'react' as-is if so.
1038+
logger.debug(
1039+
`Failed to resolve module ${color.green(`"${request}"`)} from ${color.green(issuer)}. If it's an npm package, consider adding it to dependencies or peerDependencies in package.json to make it externalized.`,
1040+
);
1041+
return request;
1042+
}
1043+
}
1044+
10101045
// Issuer is not empty string when the module is imported by another module.
10111046
// Prevent from externalizing entry modules here.
1012-
if (contextInfo.issuer) {
1047+
if (issuer) {
10131048
let resolvedRequest: string = request;
10141049

1015-
const cssExternal = cssExternalHandler(
1050+
const cssExternal = await cssExternalHandler(
10161051
resolvedRequest,
10171052
callback,
10181053
jsExtension,
10191054
cssModulesAuto,
1020-
isStyleRedirected,
1055+
styleRedirectPath,
1056+
styleRedirectExtension,
1057+
redirectPath,
10211058
);
10221059

10231060
if (cssExternal !== false) {
10241061
return cssExternal;
10251062
}
10261063

10271064
if (jsRedirectPath) {
1028-
try {
1029-
// use resolver to resolve the request
1030-
resolvedRequest = await resolver(context, resolvedRequest);
1031-
1032-
// only handle the request that is not in node_modules
1033-
if (!resolvedRequest.includes('node_modules')) {
1034-
resolvedRequest = normalizeSlash(
1035-
path.relative(
1036-
path.dirname(contextInfo.issuer),
1037-
resolvedRequest,
1038-
),
1039-
);
1040-
// Requests that fall through here cannot be matched by any other externals config ahead.
1041-
// Treat all these requests as relative import of source code. Node.js won't add the
1042-
// leading './' to the relative path resolved by `path.relative`. So add manually it here.
1043-
if (resolvedRequest[0] !== '.') {
1044-
resolvedRequest = `./${resolvedRequest}`;
1045-
}
1046-
} else {
1047-
// NOTE: If request is a phantom dependency, which means it can be resolved but not specified in dependencies or peerDependencies in package.json, the output will be incorrect to use when the package is published
1048-
// return the original request instead of the resolved request
1049-
return callback(undefined, request);
1050-
}
1051-
} catch (e) {
1052-
// catch error when request can not be resolved by resolver
1053-
// e.g. A react component library importing and using 'react' but while not defining
1054-
// it in devDependencies and peerDependencies. Preserve 'react' as-is if so.
1055-
logger.debug(
1056-
`Failed to resolve module ${color.green(`"${resolvedRequest}"`)} from ${color.green(contextInfo.issuer)}. If it's an npm package, consider adding it to dependencies or peerDependencies in package.json to make it externalized.`,
1057-
);
1058-
}
1065+
const redirectedPath = await redirectPath(resolvedRequest);
1066+
if(redirectedPath === undefined) {
1067+
return callback(undefined, request);
1068+
}
1069+
resolvedRequest = redirectedPath;
10591070
}
10601071

10611072
// Node.js ECMAScript module loader does no extension searching.

packages/core/src/css/cssConfig.ts

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -79,35 +79,53 @@ export function isCssGlobalFile(
7979

8080
type ExternalCallback = (arg0?: undefined, arg1?: string) => void;
8181

82-
export function cssExternalHandler(
82+
export async function cssExternalHandler(
8383
request: string,
8484
callback: ExternalCallback,
8585
jsExtension: string,
8686
auto: CssLoaderOptionsAuto,
87-
isStyleRedirect: boolean,
88-
): void | false {
89-
const isCssModulesRequest = isCssModulesFile(request, auto);
90-
87+
styleRedirectPath: boolean,
88+
styleRedirectExtension: boolean,
89+
redirectPath: (request: string) => Promise<string | undefined>,
90+
): Promise<false | void> {
9191
// cssExtract would execute the file handled by css-loader, so we cannot external the "helper import" from css-loader
9292
// do not external @rsbuild/core/compiled/css-loader/noSourceMaps.js, sourceMaps.js, api.mjs etc.
9393
if (/compiled\/css-loader\//.test(request)) {
9494
return callback();
9595
}
9696

97+
let resolvedRequest = request;
98+
99+
if (styleRedirectPath) {
100+
const redirectedPath = await redirectPath(request);
101+
if (redirectedPath === undefined) {
102+
return callback(undefined, request);
103+
}
104+
resolvedRequest = redirectedPath;
105+
}
106+
107+
if(!isCssFile(resolvedRequest)) {
108+
return false;
109+
}
110+
97111
// 1. css modules: import './CounterButton.module.scss' -> import './CounterButton.module.mjs'
98112
// 2. css global: import './CounterButton.scss' -> import './CounterButton.css'
99-
if (request[0] === '.' && isCssFile(request)) {
113+
if (resolvedRequest[0] === '.') {
100114
// preserve import './CounterButton.module.scss'
101-
if (!isStyleRedirect) {
102-
return callback(undefined, request);
115+
if (!styleRedirectExtension) {
116+
return callback(undefined, resolvedRequest);
103117
}
118+
const isCssModulesRequest = isCssModulesFile(resolvedRequest, auto);
104119
if (isCssModulesRequest) {
105-
return callback(undefined, request.replace(/\.[^.]+$/, jsExtension));
120+
return callback(
121+
undefined,
122+
resolvedRequest.replace(/\.[^.]+$/, jsExtension),
123+
);
106124
}
107-
return callback(undefined, request.replace(/\.[^.]+$/, '.css'));
108-
}
125+
return callback(undefined, resolvedRequest.replace(/\.[^.]+$/, '.css'));
126+
}
109127

110-
return false;
128+
return callback(undefined, request);
111129
}
112130

113131
const PLUGIN_NAME = 'rsbuild:lib-css';

packages/core/src/types/config.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,19 @@ export type JsRedirect = {
9191
extension?: boolean;
9292
};
9393

94+
export type StyleRedirect = {
95+
/**
96+
* Whether to automatically redirect the import paths of JavaScript output files.
97+
* @defaultValue `true`
98+
*/
99+
path?: boolean;
100+
/**
101+
* Whether to automatically add the file extension to import paths based on the JavaScript output files.
102+
* @defaultValue `true`
103+
*/
104+
extension?: boolean;
105+
};
106+
94107
// @ts-expect-error TODO: support dts redirect in the future
95108
type DtsRedirect = {
96109
path?: boolean;
@@ -101,7 +114,7 @@ export type Redirect = {
101114
/** Controls the redirect of the import paths of output JavaScript files. */
102115
js?: JsRedirect;
103116
/** Whether to redirect the import path of the style file. */
104-
style?: boolean;
117+
style?: StyleRedirect;
105118
// TODO: support other redirects
106119
// asset?: boolean;
107120
// dts?: DtsRedirect;

pnpm-lock.yaml

Lines changed: 3 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tests/integration/redirect/style-false/rslib.config.ts renamed to tests/integration/redirect/style-extension/rslib.config.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,27 @@ export default defineConfig({
66
generateBundleEsmConfig({
77
bundle: false,
88
redirect: {
9-
style: false,
9+
style: {
10+
extension: false,
11+
},
1012
},
1113
}),
1214
generateBundleCjsConfig({
1315
bundle: false,
1416
redirect: {
15-
style: false,
17+
style: {
18+
extension: false,
19+
},
1620
},
1721
}),
1822
],
1923
source: {
2024
entry: {
21-
index: ['./src/index.ts'],
25+
index: ['./src/**', '!./src/**/*.less'],
2226
},
2327
},
2428
output: {
2529
target: 'web',
26-
copy: [{ from: './src/index.less' }, { from: './src/style.module.less' }],
30+
copy: [{ from: './**/*.less', context: './src' }],
2731
},
2832
});
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
import './index.less';
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// @ts-ignore env.d.ts
2+
import styles from './index.module.less';
3+
4+
styles;

tests/integration/redirect/style-false/src/index.ts

Lines changed: 0 additions & 4 deletions
This file was deleted.
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"name": "redirect-js-import-css-test",
3+
"version": "1.0.0",
4+
"private": true,
5+
"type": "module"
6+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { defineConfig } from '@rslib/core';
2+
import { generateBundleCjsConfig, generateBundleEsmConfig } from 'test-helper';
3+
4+
export default defineConfig({
5+
lib: [
6+
generateBundleEsmConfig({
7+
bundle: false,
8+
}),
9+
generateBundleCjsConfig({
10+
bundle: false,
11+
}),
12+
],
13+
source: {
14+
entry: {
15+
index: ['./src/**'],
16+
},
17+
},
18+
output: {
19+
target: 'web',
20+
},
21+
});
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
.foo {
2+
color: red;
3+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
import '@/css/index.css';
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
.foo {
2+
color: red;
3+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// @ts-ignore env.d.ts
2+
import styles from '@/module/index.module.css';
3+
4+
styles;
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"extends": "@rslib/tsconfig/base",
3+
"compilerOptions": {
4+
"baseUrl": "./",
5+
"paths": {
6+
"@/*": ["./src/*"]
7+
}
8+
},
9+
"include": ["src"]
10+
}

tests/integration/redirect/style.test.ts

Lines changed: 0 additions & 28 deletions
This file was deleted.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import path from 'node:path';
2+
import { buildAndGetResults, getFileBySuffix } from 'test-helper';
3+
import { expect, test } from 'vitest';
4+
5+
test('should extract css successfully when using redirect.style = false', async () => {
6+
const fixturePath = path.resolve(__dirname, './style-extension');
7+
const { contents } = await buildAndGetResults({ fixturePath });
8+
const esmFiles = Object.keys(contents.esm);
9+
expect(esmFiles).toMatchInlineSnapshot(`
10+
[
11+
"<ROOT>/tests/integration/redirect/style-extension/dist/esm/less/index.js",
12+
"<ROOT>/tests/integration/redirect/style-extension/dist/esm/module/index.js",
13+
]
14+
`);
15+
const lessIndexJs = getFileBySuffix(contents.esm, 'less/index.js');
16+
expect(lessIndexJs).toMatchInlineSnapshot(`
17+
"import "./index.less";
18+
"
19+
`);
20+
const lessModuleIndexJs = getFileBySuffix(contents.esm, 'module/index.js');
21+
expect(lessModuleIndexJs).toMatchInlineSnapshot(`
22+
"import * as __WEBPACK_EXTERNAL_MODULE__index_module_less__ from "./index.module.less";
23+
__WEBPACK_EXTERNAL_MODULE__index_module_less__["default"];
24+
"
25+
`);
26+
27+
const cjsFiles = Object.keys(contents.cjs);
28+
expect(cjsFiles).toMatchInlineSnapshot(`
29+
[
30+
"<ROOT>/tests/integration/redirect/style-extension/dist/cjs/less/index.cjs",
31+
"<ROOT>/tests/integration/redirect/style-extension/dist/cjs/module/index.cjs",
32+
]
33+
`);
34+
const lessIndexCjs = getFileBySuffix(contents.cjs, 'less/index.cjs');
35+
expect(lessIndexCjs).toContain('require("./index.less");');
36+
const lessModuleIndexCjs = getFileBySuffix(contents.cjs, 'module/index.cjs');
37+
expect(lessModuleIndexCjs).toContain('require("./index.module.less")');
38+
});

0 commit comments

Comments
 (0)