Skip to content
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

refactor(core): rewrite Webpack ChunkAssetPlugin with RuntimeModule #10485

Merged
merged 6 commits into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 1 addition & 1 deletion .github/workflows/build-perf.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ jobs:
repo-token: ${{ secrets.GITHUB_TOKEN }}
build-script: build:website:fast
clean-script: clear:website # see https://github.com/facebook/docusaurus/pull/6838
pattern: '{website/build/assets/js/main*js,website/build/assets/css/styles*css,website/.docusaurus/globalData.json,website/.docusaurus/registry.js,website/.docusaurus/routes.js,website/.docusaurus/routesChunkNames.json,website/.docusaurus/site-metadata.json,website/.docusaurus/codeTranslations.json,website/.docusaurus/i18n.json,website/.docusaurus/docusaurus.config.mjs,website/build/index.html,website/build/docs.html,website/build/docs/**/*.html,website/build/blog.html,website/build/blog/**/*.html}'
pattern: '{website/build/assets/js/main*js,website/build/assets/js/runtime~main*js,website/build/assets/css/styles*css,website/.docusaurus/globalData.json,website/.docusaurus/registry.js,website/.docusaurus/routes.js,website/.docusaurus/routesChunkNames.json,website/.docusaurus/site-metadata.json,website/.docusaurus/codeTranslations.json,website/.docusaurus/i18n.json,website/.docusaurus/docusaurus.config.mjs,website/build/index.html,website/build/docs.html,website/build/docs/**/*.html,website/build/blog.html,website/build/blog/**/*.html}'
# HTML files: exclude versioned docs pages, tags pages, html redirect files
exclude: '{website/build/docs/?.?.?/**/*.html,website/build/docs/next/**/*.html,website/build/blog/tags/**/*.html,**/*.html.html}'
strip-hash: '\.([^;]\w{7})\.'
Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus/src/webpack/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {BundleAnalyzerPlugin} from 'webpack-bundle-analyzer';
import ReactLoadableSSRAddon from 'react-loadable-ssr-addon-v5-slorber';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import {createBaseConfig} from './base';
import ChunkAssetPlugin from './plugins/ChunkAssetPlugin';
import GetChunkAssetRuntimePlugin from './plugins/GetChunkAssetRuntimePlugin';
import CleanWebpackPlugin from './plugins/CleanWebpackPlugin';
import ForceTerminatePlugin from './plugins/ForceTerminatePlugin';
import {createStaticDirectoriesCopyPlugin} from './plugins/StaticDirectoriesCopyPlugin';
Expand Down Expand Up @@ -52,7 +52,7 @@ async function createBaseClientConfig({
new webpack.DefinePlugin({
'process.env.HYDRATE_CLIENT_ENTRY': JSON.stringify(hydrate),
}),
new ChunkAssetPlugin(),
new GetChunkAssetRuntimePlugin(),
// Show compilation progress bar and build time.
new WebpackBar({
name: 'Client',
Expand Down
55 changes: 0 additions & 55 deletions packages/docusaurus/src/webpack/plugins/ChunkAssetPlugin.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import webpack, {type Compiler} from 'webpack';

const PluginName = 'Docusaurus-ChunkAssetPlugin';

// This generates a __webpack_require__.gca fn to the Webpack runtime chunk
// It is called in docusaurus.ts for chunk prefetching
function generateGetChunkAssetRuntimeCode(chunk: webpack.Chunk): string {
const chunkIdToName = chunk.getChunkMaps(false).name;
const chunkNameToId = Object.fromEntries(
Object.entries(chunkIdToName).map(([chunkId, chunkName]) => [
chunkName,
chunkId,
]),
);

// Custom Docusaurus runtime function to convert from chunkId to chunk url
const DocusaurusGetChunkAsset = '__webpack_require__.gca';

const {
// publicPath = __webpack_require__.p
// Example: "/" or "/baseUrl/"
// https://github.com/webpack/webpack/blob/v5.94.0/lib/runtime/PublicPathRuntimeModule.js
publicPath,

// getChunkScriptFilename = __webpack_require__.u
// Example: getChunkScriptFilename("814f3328") = "814f3328.03fcc178.js"
// https://github.com/webpack/webpack/blob/v5.94.0/lib/runtime/GetChunkFilenameRuntimeModule.js
getChunkScriptFilename,
} = webpack.RuntimeGlobals;

const code = `// Docusaurus function to get chunk asset
${DocusaurusGetChunkAsset} = function(chunkId) { chunkId = ${JSON.stringify(
chunkNameToId,
)}[chunkId]||chunkId; return ${publicPath} + ${getChunkScriptFilename}(chunkId); };`;
Fixed Show fixed Hide fixed

return webpack.Template.asString(code);
}

/*
Note: we previously used "mainTemplate.hooks.requireExtensions.tap"
But it will be removed in Webpack 6 and is not supported by Rspack

Check failure on line 48 in packages/docusaurus/src/webpack/plugins/GetChunkAssetRuntimePlugin.ts

View workflow job for this annotation

GitHub Actions / Lint

Unknown word (Rspack) -- is not supported by Rspack
So instead we use equivalent code inspired by:
- https://github.com/webpack/webpack/blob/v5.94.0/lib/RuntimePlugin.js#L462
- https://github.com/webpack/webpack/blob/v5.94.0/lib/runtime/CompatRuntimeModule.js
*/
export default class GetChunkAssetRuntimePlugin {
apply(compiler: Compiler): void {
compiler.hooks.thisCompilation.tap(PluginName, (compilation) => {
compilation.hooks.additionalTreeRuntimeRequirements.tap(
PluginName,
(chunk) => {
compilation.addRuntimeModule(chunk, new ChunkAssetRuntimeModule());
},
);
});
}
}

// Inspired by https://github.com/webpack/webpack/blob/v5.94.0/lib/runtime/CompatRuntimeModule.js
class ChunkAssetRuntimeModule extends webpack.RuntimeModule {
constructor() {
super('compat', webpack.RuntimeModule.STAGE_ATTACH);
this.fullHash = true;
}

override generate() {
return generateGetChunkAssetRuntimeCode(this.chunk!);
}
}
2 changes: 0 additions & 2 deletions packages/docusaurus/src/webpack/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@ export default async function createServerConfig(params: {
path: outputDir,
filename: outputFilename,
libraryTarget: 'commonjs2',
// Workaround for Webpack 4 Bug (https://github.com/webpack/webpack/issues/6522)
globalObject: 'this',
},
plugins: [
// Show compilation progress bar.
Expand Down
Loading