Skip to content
Draft
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
5 changes: 4 additions & 1 deletion packages/docusaurus-bundler/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,8 @@ export {getClientQueries, getTargets} from './browserslist';
export {getMinimizers} from './minification';
export {getHtmlMinifier, type HtmlMinifier} from './minifyHtml';
export {createJsLoaderFactory} from './loaders/jsLoader';
export {createStyleLoadersFactory} from './loaders/styleLoader';
export {
createStyleLoadersFactory,
getNativeStyleLoaders,
} from './loaders/styleLoader';
export {RspackDevServer} from './rspack';
78 changes: 53 additions & 25 deletions packages/docusaurus-bundler/src/loaders/styleLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import {getCSSExtractPlugin} from '../currentBundler';
import {getClientQueries} from '../browserslist';
import type {ConfigureWebpackUtils, CurrentBundler} from '@docusaurus/types';

type Loader = {loader: string; options?: {[key: string]: unknown}};

export async function createStyleLoadersFactory({
currentBundler,
}: {
Expand Down Expand Up @@ -39,7 +41,7 @@ export async function createStyleLoadersFactory({
},
]
: // Ignore regular CSS files
[{loader: require.resolve('./nullLoader')}];
[getNullLoader()];
}

return [
Expand All @@ -59,30 +61,56 @@ export async function createStyleLoadersFactory({
// But in practice, it's not a big deal because css-loader also uses postcss
// and is able to reuse the parsed AST from postcss-loader
// See https://github.com/webpack-contrib/css-loader/blob/master/src/index.js#L159
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
postcssOptions: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
plugins: [
[
require.resolve('postcss-preset-env'),
{
// Otherwise, preset-env ignores the Docusaurus default
// queries, and Autoprefixer reads the config of each CSS
// file's path
browsers: getClientQueries(),
},
],
],
},
},
},
getPostCssLoader(),
];
};
}

/**
* The loaders to use with the Rspack native CSS rule types ("css" and
* "css/module"), which replace css-loader and CssExtractRspackPlugin.
*/
export function getNativeStyleLoaders({
isServer,
isCssModule,
}: {
isServer: boolean;
isCssModule: boolean;
}): Loader[] {
// On the server we don't need to emit CSS, only CSS module class names
if (isServer) {
return isCssModule ? [] : [getNullLoader()];
}
return [getPostCssLoader()];
}

function getNullLoader(): Loader {
return {loader: require.resolve('./nullLoader')};
}

function getPostCssLoader(): Loader {
return {
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
postcssOptions: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
plugins: [
[
require.resolve('postcss-preset-env'),
{
// Otherwise, preset-env ignores the Docusaurus default
// queries, and Autoprefixer reads the config of each CSS
// file's path
browsers: getClientQueries(),
},
],
],
},
},
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,34 @@ describe('PostCssPluginWrapInLayer', () => {
]).process('a{left:var(--width)}', {from: '/site/file.css'});

expect(result.css).toMatchInlineSnapshot(
`"@layer myLayer{a{right:1px;right:var(--width)}}"`,
`"@layer myLayer;@layer myLayer{a{right:1px;right:var(--width)}}"`,
);
});

const layers = {
'layer.a': (filePath: string) => filePath.endsWith('a.css'),
'layer.b': (filePath: string) => filePath.endsWith('b.css'),
};

async function processCss(css: string, filePath: string): Promise<string> {
const result = await postcss([PostCssPluginWrapInLayer({layers})]).process(
css,
{from: filePath},
);
return result.css;
}

it('wraps the file in its layer, after the layers declaration', async () => {
await expect(
processCss('.a { color: red; }', '/site/b.css'),
).resolves.toMatchInlineSnapshot(
`"@layer layer.a, layer.b;@layer layer.b {.a { color: red; } }"`,
);
});

it('does not change a file without layer', async () => {
await expect(
processCss('.a { color: red; }', '/site/c.css'),
).resolves.toMatchInlineSnapshot(`".a { color: red; }"`);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@ import {findLayer} from './layers';
import type {Helpers, Root, PluginCreator} from 'postcss';
import type {PluginOptions} from './options';

// The layer order is the order of first appearance in the CSS bundle
// Declaring it in each file makes it independent of the bundler CSS order
// See https://github.com/meta/docusaurus/pull/13032
function prependLayersDeclaration(
root: Root,
layerNames: string[],
{AtRule}: Helpers,
): void {
root.prepend(new AtRule({name: 'layer', params: layerNames.join(', ')}));
}

function wrapCssRootInLayer(
root: Root,
layer: string,
Expand All @@ -26,6 +37,7 @@ export const PostCssPluginWrapInLayer: PluginCreator<{
throw new Error('PostCssPluginWrapInLayer options are mandatory');
}
const layers = Object.entries(options.layers);
const layerNames = Object.keys(options.layers);
return {
postcssPlugin: 'postcss-wrap-in-layer',
Once(root, helpers) {
Expand All @@ -36,6 +48,7 @@ export const PostCssPluginWrapInLayer: PluginCreator<{
const layer = findLayer(filePath, layers);
if (layer) {
wrapCssRootInLayer(root, layer, helpers);
prependLayersDeclaration(root, layerNames, helpers);
}
},
};
Expand Down
139 changes: 103 additions & 36 deletions packages/docusaurus/src/webpack/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
createJsLoaderFactory,
getCSSExtractPlugin,
getMinimizers,
getNativeStyleLoaders,
getTargets,
} from '@docusaurus/bundler';
import {
Expand Down Expand Up @@ -179,8 +180,101 @@ export async function createBaseConfig({
};
}

function cssFilename() {
return isProd ? `assets/css/[name].${contentHash}.css` : '[name].css';
}

const notTextImport: RuleSetRule['with'] = {type: {not: 'text'}};

function getCssRules(): RuleSetRule[] {
if (props.currentBundler.name === 'rspack') {
return getNativeCssRules();
}
return getCssLoaderRules();
}

// Rspack parses, bundles and emits CSS natively, without css-loader
// See https://rspack.rs/guide/tech/css
function getNativeCssRules(): RuleSetRule[] {
return [
{
test: CSS_REGEX,
exclude: CSS_MODULE_REGEX,
with: notTextImport,
// On the server, the null loader turns CSS files into empty JS modules
type: isServer ? undefined : 'css',
use: getNativeStyleLoaders({isServer, isCssModule: false}),
},
{
test: CSS_MODULE_REGEX,
with: notTextImport,
type: 'css/module',
use: getNativeStyleLoaders({isServer, isCssModule: true}),
parser: {
// Docusaurus code imports CSS modules with a default import
namedExports: false,
// Only rename class names and @keyframes, like css-loader
dashedIdents: false,
container: false,
customIdents: false,
grid: false,
function: false,
},
generator: {
// [contenthash] differs between the client and server compilers
localIdentName: '[local]_[hash]',
localIdentHashDigest: 'base64url',
localIdentHashDigestLength: 4,
exportsOnly: isServer,
exportsConvention: 'as-is',
},
},
];
}

function getCssLoaderRules(): RuleSetRule[] {
return [
{
test: CSS_REGEX,
exclude: CSS_MODULE_REGEX,
with: notTextImport,
use: configureWebpackUtils.getStyleLoaders(isServer, {
importLoaders: 1,
sourceMap: !isProd,
}),
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: CSS_MODULE_REGEX,
with: notTextImport,
use: configureWebpackUtils.getStyleLoaders(isServer, {
modules: {
// Using the same CSS Module class pattern in dev/prod on purpose
// See https://github.com/meta/docusaurus/pull/10423
localIdentName: `[local]_[contenthash:base64:4]`,
exportOnlyLocals: isServer,
// Export CSS module class names compatible with css-loader v6
// export ".themedComponent--dark" instead of .themedComponentDark
// See https://github.com/webpack/css-loader/releases/tag/v7.0.0
exportLocalsConvention: 'as-is',
},
importLoaders: 1,
sourceMap: !isProd,
}),
},
];
}

// Same as CSSExtractPlugin "ignoreOrder", which native CSS doesn't have
// See https://github.com/webpack-contrib/mini-css-extract-plugin/pull/422
function getIgnoreWarnings(): Configuration['ignoreWarnings'] {
if (props.currentBundler.name === 'rspack') {
return [/Conflicting order/];
}
return undefined;
}

return {
mode,
name,
Expand All @@ -192,10 +286,13 @@ export async function createBaseConfig({
chunkFilename: isProd
? `assets/js/[name].${contentHash}.js`
: '[name].js',
cssFilename: cssFilename(),
cssChunkFilename: cssFilename(),
publicPath:
siteConfig.future.experimental_router === 'hash' ? 'auto' : baseUrl,
hashFunction: 'xxhash64',
},
ignoreWarnings: getIgnoreWarnings(),
// Don't throw warning when asset created is over 250kb
performance: {
hints: false,
Expand Down Expand Up @@ -270,7 +367,9 @@ export async function createBaseConfig({
// See https://github.com/meta/docusaurus/issues/2006
styles: {
name: 'styles',
type: 'css/mini-extract',
// "css/mini-extract" for CSSExtractPlugin, "css" and
// "css/module" for Rspack native CSS
type: /^css(?:\/|$)/,
chunks: `all`,
enforce: true,
priority: 50,
Expand All @@ -297,45 +396,13 @@ export async function createBaseConfig({
with: notTextImport,
use: [createJsLoader({isServer})],
},
{
test: CSS_REGEX,
exclude: CSS_MODULE_REGEX,
with: notTextImport,
use: configureWebpackUtils.getStyleLoaders(isServer, {
importLoaders: 1,
sourceMap: !isProd,
}),
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: CSS_MODULE_REGEX,
with: notTextImport,
use: configureWebpackUtils.getStyleLoaders(isServer, {
modules: {
// Using the same CSS Module class pattern in dev/prod on purpose
// See https://github.com/meta/docusaurus/pull/10423
localIdentName: `[local]_[contenthash:base64:4]`,
exportOnlyLocals: isServer,
// Export CSS module class names compatible with css-loader v6
// export ".themedComponent--dark" instead of .themedComponentDark
// See https://github.com/webpack/css-loader/releases/tag/v7.0.0
exportLocalsConvention: 'as-is',
},
importLoaders: 1,
sourceMap: !isProd,
}),
},
...getCssRules(),
],
},
plugins: [
new CSSExtractPlugin({
filename: isProd
? `assets/css/[name].${contentHash}.css`
: '[name].css',
chunkFilename: isProd
? `assets/css/[name].${contentHash}.css`
: '[name].css',
filename: cssFilename(),
chunkFilename: cssFilename(),
// Remove css order warnings if css imports are not sorted
// alphabetically. See https://github.com/webpack-contrib/mini-css-extract-plugin/pull/422
// for more reasoning
Expand Down
1 change: 1 addition & 0 deletions project-words.txt
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ Husain
Héctor
héllô
IANAD
Idents
Infima
infima
infimum
Expand Down
3 changes: 2 additions & 1 deletion website/src/pages/styles.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ html[data-theme='dark'] .topBannerTitleText {
}

/* Used to test CSS insertion order */
.test-marker-site-index-page {
/* Global: Rspack removes the unused CSS module classes */
:global(.test-marker-site-index-page) {
content: 'site-index-page';
}
3 changes: 2 additions & 1 deletion website/src/theme/Layout/styles.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

/* Used to test CSS insertion order */
.test-marker-theme-layout {
/* Global: Rspack removes the unused CSS module classes */
:global(.test-marker-theme-layout) {
content: 'theme-layout';
}
Loading