Skip to content

Commit 81c4353

Browse files
committed
chore: update
1 parent cf7ff5e commit 81c4353

File tree

23 files changed

+225
-86
lines changed

23 files changed

+225
-86
lines changed

packages/core/src/config.ts

Lines changed: 33 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -978,7 +978,8 @@ const composeBundlelessExternalConfig = (
978978
} => {
979979
if (bundle) return { config: {} };
980980

981-
const isStyleRedirected = redirect.style ?? true;
981+
const styleRedirectPath = redirect.style?.path ?? true;
982+
const styleRedirectExtension = redirect.style?.extension ?? true;
982983
const jsRedirectPath = redirect.js?.path ?? true;
983984
const jsRedirectExtension = redirect.js?.extension ?? true;
984985

@@ -997,50 +998,57 @@ const composeBundlelessExternalConfig = (
997998
if (!request || !getResolve || !context || !contextInfo) {
998999
return callback();
9991000
}
1001+
const { issuer } = contextInfo;
10001002

10011003
if (!resolver) {
10021004
resolver = (await getResolve()) as RspackResolver;
10031005
}
10041006

1007+
async function redirectPath(request: string): Promise<string> {
1008+
try {
1009+
let resolvedRequest = request;
1010+
resolvedRequest = await resolver!(context!, resolvedRequest);
1011+
resolvedRequest = normalizeSlash(
1012+
path.relative(path.dirname(issuer), resolvedRequest),
1013+
);
1014+
// Requests that fall through here cannot be matched by any other externals config ahead.
1015+
// Treat all these requests as relative import of source code. Node.js won't add the
1016+
// leading './' to the relative path resolved by `path.relative`. So add manually it here.
1017+
if (resolvedRequest[0] !== '.') {
1018+
resolvedRequest = `./${resolvedRequest}`;
1019+
}
1020+
return resolvedRequest;
1021+
} catch (e) {
1022+
// e.g. A react component library importing and using 'react' but while not defining
1023+
// it in devDependencies and peerDependencies. Preserve 'react' as-is if so.
1024+
logger.warn(
1025+
`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.`,
1026+
);
1027+
return request;
1028+
}
1029+
}
1030+
10051031
// Issuer is not empty string when the module is imported by another module.
10061032
// Prevent from externalizing entry modules here.
1007-
if (contextInfo.issuer) {
1033+
if (issuer) {
10081034
let resolvedRequest: string = request;
10091035

1010-
const cssExternal = cssExternalHandler(
1036+
const cssExternal = await cssExternalHandler(
10111037
resolvedRequest,
10121038
callback,
10131039
jsExtension,
10141040
cssModulesAuto,
1015-
isStyleRedirected,
1041+
styleRedirectPath,
1042+
styleRedirectExtension,
1043+
redirectPath,
10161044
);
10171045

10181046
if (cssExternal !== false) {
10191047
return cssExternal;
10201048
}
10211049

10221050
if (jsRedirectPath) {
1023-
try {
1024-
resolvedRequest = await resolver(context, resolvedRequest);
1025-
resolvedRequest = normalizeSlash(
1026-
path.relative(
1027-
path.dirname(contextInfo.issuer),
1028-
resolvedRequest,
1029-
),
1030-
);
1031-
// Requests that fall through here cannot be matched by any other externals config ahead.
1032-
// Treat all these requests as relative import of source code. Node.js won't add the
1033-
// leading './' to the relative path resolved by `path.relative`. So add manually it here.
1034-
if (resolvedRequest[0] !== '.') {
1035-
resolvedRequest = `./${resolvedRequest}`;
1036-
}
1037-
} catch (e) {
1038-
// e.g. A react component library importing and using 'react' but while not defining
1039-
// it in devDependencies and peerDependencies. Preserve 'react' as-is if so.
1040-
logger.warn(
1041-
`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.`,
1042-
);
1043-
}
1051+
resolvedRequest = await redirectPath(resolvedRequest);
10441052
}
10451053

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

packages/core/src/css/cssConfig.ts

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -79,32 +79,39 @@ 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, emitWarning: boolean) => Promise<string>
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+
resolvedRequest = await redirectPath(request, false);
101+
}
102+
97103
// 1. css modules: import './CounterButton.module.scss' -> import './CounterButton.module.mjs'
98104
// 2. css global: import './CounterButton.scss' -> import './CounterButton.css'
99-
if (request[0] === '.' && isCssFile(request)) {
105+
if (resolvedRequest[0] === '.' && isCssFile(resolvedRequest)) {
100106
// preserve import './CounterButton.module.scss'
101-
if (!isStyleRedirect) {
102-
return callback(undefined, request);
107+
if (!styleRedirectExtension) {
108+
return callback(undefined, resolvedRequest);
103109
}
110+
const isCssModulesRequest = isCssModulesFile(resolvedRequest, auto);
104111
if (isCssModulesRequest) {
105-
return callback(undefined, request.replace(/\.[^.]+$/, jsExtension));
112+
return callback(undefined, resolvedRequest.replace(/\.[^.]+$/, jsExtension));
106113
}
107-
return callback(undefined, request.replace(/\.[^.]+$/, '.css'));
114+
return callback(undefined, resolvedRequest.replace(/\.[^.]+$/, '.css'));
108115
}
109116

110117
return false;

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_d1c6f702__ from "./index.module.less";
23+
__WEBPACK_EXTERNAL_MODULE__index_module_less_d1c6f702__["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+
});
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import path from 'node:path';
2+
import { buildAndGetResults, getFileBySuffix } from 'test-helper';
3+
import { expect, test } from 'vitest';
4+
5+
test('should handle the crossing case import "@/css/button.css"', async () => {
6+
const fixturePath = path.resolve(__dirname, './style-path');
7+
const { contents } = await buildAndGetResults({ fixturePath });
8+
console.log(contents);
9+
const esmFiles = Object.keys(contents.esm);
10+
expect(esmFiles).toMatchInlineSnapshot(`
11+
[
12+
"<ROOT>/tests/integration/redirect/style-path/dist/esm/css/index.js",
13+
"<ROOT>/tests/integration/redirect/style-path/dist/esm/module/index.js",
14+
"<ROOT>/tests/integration/redirect/style-path/dist/esm/module/index.module.js",
15+
]
16+
`);
17+
const cssIndexJs = getFileBySuffix(contents.esm, 'css/index.js');
18+
expect(cssIndexJs).toMatchInlineSnapshot(`
19+
"import "./index.css";
20+
"
21+
`);
22+
const cssModuleIndexJs = getFileBySuffix(contents.esm, 'module/index.js');
23+
expect(cssModuleIndexJs).toMatchInlineSnapshot(`
24+
"import * as __WEBPACK_EXTERNAL_MODULE__index_module_js_6796f91d__ from "./index.module.js";
25+
__WEBPACK_EXTERNAL_MODULE__index_module_js_6796f91d__["default"];
26+
"
27+
`);
28+
29+
const cjsFiles = Object.keys(contents.cjs);
30+
expect(cjsFiles).toMatchInlineSnapshot(`
31+
[
32+
"<ROOT>/tests/integration/redirect/style-path/dist/cjs/css/index.cjs",
33+
"<ROOT>/tests/integration/redirect/style-path/dist/cjs/module/index.cjs",
34+
"<ROOT>/tests/integration/redirect/style-path/dist/cjs/module/index.module.cjs",
35+
]
36+
`);
37+
const cssIndexCjs = getFileBySuffix(contents.cjs, 'css/index.cjs');
38+
expect(cssIndexCjs).toContain('require("./index.css")');
39+
const cssModuleIndexCjs = getFileBySuffix(contents.cjs, 'module/index.cjs');
40+
expect(cssModuleIndexCjs).toContain('require("./index.module.cjs")');
41+
});

0 commit comments

Comments
 (0)