Skip to content

feat!: support redirect.style.path and redirect.style.extension #618

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 47 additions & 34 deletions packages/core/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -983,7 +983,8 @@ const composeBundlelessExternalConfig = (
} => {
if (bundle) return { config: {} };

const isStyleRedirected = redirect.style ?? true;
const styleRedirectPath = redirect.style?.path ?? true;
const styleRedirectExtension = redirect.style?.extension ?? true;
const jsRedirectPath = redirect.js?.path ?? true;
const jsRedirectExtension = redirect.js?.extension ?? true;

Expand All @@ -1002,60 +1003,72 @@ const composeBundlelessExternalConfig = (
if (!request || !getResolve || !context || !contextInfo) {
return callback();
}
const { issuer } = contextInfo;

if (!resolver) {
resolver = (await getResolve()) as RspackResolver;
}

async function redirectPath(
request: string,
): Promise<string | undefined> {
try {
let resolvedRequest = request;
// use resolver to resolve the request
resolvedRequest = await resolver!(context!, resolvedRequest);

// only handle the request that is not in node_modules
if (!resolvedRequest.includes('node_modules')) {
resolvedRequest = normalizeSlash(
path.relative(path.dirname(issuer), resolvedRequest),
);
// Requests that fall through here cannot be matched by any other externals config ahead.
// Treat all these requests as relative import of source code. Node.js won't add the
// leading './' to the relative path resolved by `path.relative`. So add manually it here.
if (resolvedRequest[0] !== '.') {
resolvedRequest = `./${resolvedRequest}`;
}
return resolvedRequest;
}
// 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
// return the original request instead of the resolved request
return undefined;
} catch (e) {
// catch error when request can not be resolved by resolver
// e.g. A react component library importing and using 'react' but while not defining
// it in devDependencies and peerDependencies. Preserve 'react' as-is if so.
logger.debug(
`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.`,
);
return request;
}
}

// Issuer is not empty string when the module is imported by another module.
// Prevent from externalizing entry modules here.
if (contextInfo.issuer) {
if (issuer) {
let resolvedRequest: string = request;

const cssExternal = cssExternalHandler(
const cssExternal = await cssExternalHandler(
resolvedRequest,
callback,
jsExtension,
cssModulesAuto,
isStyleRedirected,
styleRedirectPath,
styleRedirectExtension,
redirectPath,
);

if (cssExternal !== false) {
return cssExternal;
}

if (jsRedirectPath) {
try {
// use resolver to resolve the request
resolvedRequest = await resolver(context, resolvedRequest);

// only handle the request that is not in node_modules
if (!resolvedRequest.includes('node_modules')) {
resolvedRequest = normalizeSlash(
path.relative(
path.dirname(contextInfo.issuer),
resolvedRequest,
),
);
// Requests that fall through here cannot be matched by any other externals config ahead.
// Treat all these requests as relative import of source code. Node.js won't add the
// leading './' to the relative path resolved by `path.relative`. So add manually it here.
if (resolvedRequest[0] !== '.') {
resolvedRequest = `./${resolvedRequest}`;
}
} else {
// 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
// return the original request instead of the resolved request
return callback(undefined, request);
}
} catch (e) {
// catch error when request can not be resolved by resolver
// e.g. A react component library importing and using 'react' but while not defining
// it in devDependencies and peerDependencies. Preserve 'react' as-is if so.
logger.debug(
`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.`,
);
const redirectedPath = await redirectPath(resolvedRequest);
if (redirectedPath === undefined) {
return callback(undefined, request);
}
resolvedRequest = redirectedPath;
}

// Node.js ECMAScript module loader does no extension searching.
Expand Down
39 changes: 26 additions & 13 deletions packages/core/src/css/cssConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,35 +79,48 @@ export function isCssGlobalFile(

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

export function cssExternalHandler(
export async function cssExternalHandler(
request: string,
callback: ExternalCallback,
jsExtension: string,
auto: CssLoaderOptionsAuto,
isStyleRedirect: boolean,
): void | false {
const isCssModulesRequest = isCssModulesFile(request, auto);

styleRedirectPath: boolean,
styleRedirectExtension: boolean,
redirectPath: (request: string) => Promise<string | undefined>,
): Promise<false | void> {
// cssExtract would execute the file handled by css-loader, so we cannot external the "helper import" from css-loader
// do not external @rsbuild/core/compiled/css-loader/noSourceMaps.js, sourceMaps.js, api.mjs etc.
if (/compiled\/css-loader\//.test(request)) {
return callback();
}

let resolvedRequest = request;

if (styleRedirectPath) {
const resolved = await redirectPath(resolvedRequest);
if (resolved) {
resolvedRequest = resolved;
}
}

if (!isCssFile(resolvedRequest)) {
return false;
}

// 1. css modules: import './CounterButton.module.scss' -> import './CounterButton.module.mjs'
// 2. css global: import './CounterButton.scss' -> import './CounterButton.css'
if (request[0] === '.' && isCssFile(request)) {
// preserve import './CounterButton.module.scss'
if (!isStyleRedirect) {
return callback(undefined, request);
}
if (styleRedirectExtension) {
const isCssModulesRequest = isCssModulesFile(resolvedRequest, auto);
if (isCssModulesRequest) {
return callback(undefined, request.replace(/\.[^.]+$/, jsExtension));
return callback(
undefined,
resolvedRequest.replace(/\.[^.]+$/, jsExtension),
);
}
return callback(undefined, request.replace(/\.[^.]+$/, '.css'));
return callback(undefined, resolvedRequest.replace(/\.[^.]+$/, '.css'));
}

return false;
return callback(undefined, resolvedRequest);
}

const PLUGIN_NAME = 'rsbuild:lib-css';
Expand Down
15 changes: 14 additions & 1 deletion packages/core/src/types/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,19 @@ export type JsRedirect = {
extension?: boolean;
};

export type StyleRedirect = {
/**
* Whether to automatically redirect the import paths of style output files.
* @defaultValue `true`
*/
path?: boolean;
/**
* Whether to automatically add the file extension to import paths based on the style output files.
* @defaultValue `true`
*/
extension?: boolean;
};

// @ts-expect-error TODO: support dts redirect in the future
type DtsRedirect = {
path?: boolean;
Expand All @@ -101,7 +114,7 @@ export type Redirect = {
/** Controls the redirect of the import paths of output JavaScript files. */
js?: JsRedirect;
/** Whether to redirect the import path of the style file. */
style?: boolean;
style?: StyleRedirect;
// TODO: support other redirects
// asset?: boolean;
// dts?: DtsRedirect;
Expand Down
2 changes: 1 addition & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 0 additions & 28 deletions tests/integration/redirect/style-false/rslib.config.ts

This file was deleted.

4 changes: 0 additions & 4 deletions tests/integration/redirect/style-false/src/index.ts

This file was deleted.

Loading
Loading