Unverified Commit d7d636ad authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Tree shake the unused exports in direct relative imported client component module (#62238)

### What & Why

This PR helps fixes a long time tree-shaking issue that if you're import
some identifiers from client components, the whole client component is
being included in the client chunk. Because we're using import eager
mode in webpack to include all the client component modules that make
sure they're present in SSR entry and browser entry when they're
transformed to client reference on RSC layer.

But the way we collect client components is a bit "aggressive" where
contains some spaces to optimize.

### How

We change the collected client components from simpliy collecting it
resolved module request, into collecting both the imported identifiers
(by server components) and the module request. And when we inserted the
used client components imports into the SSR and Client entry, leverage
webpack magic comments `"webpackExports"` to only contain the used
exports in the bundle. Thank you webpack for this nice feature : )

Along the way we also fixed an issue that when you only used default
export, the `default` export itself should also be proxied when the
bundle is in ESM.

#### Notice

There's a limitation yet that it can't work with barrel file, if you
have a shared component `index.js` to re-export the changes several
client components there and you only partially import few from
`index.js` it won't work. For the cases that the node_modules package
contain a barrel file importing multiple client components, please use
[optimizePackageImports](https://nextjs.org/docs/app/api-reference/next-config-js/optimizePackageImports)
config for now. We'll have follow up optimizations

### Testing Result

If we compare the `react-aria-components` the reproduction from #60246,
you'll see the result being optimized a lot:

#### After vs Before

134KB being tree-shaked out 🤯 
```
Route (app)                              Size     First Load JS
┌ ○ /                                    324 B           127 kB
├ ○ /_not-found                          872 B          86.5 kB
└ ○ /other-page                          174 B           127 kB
```

```
Route (app)                              Size     First Load JS
┌ ○ /                                    325 B           261 kB
├ ○ /_not-found                          870 B          86.5 kB
└ ○ /other-page                          176 B           261 kB
```

Fixes #60246
Related report: https://github.com/adobe/react-spectrum/issues/5639
Closes NEXT-2527
phase 1 of NEXT-1799

---------
Co-authored-by: 's avatarShu Ding <g@shud.in>
parent 09c0065c
...@@ -125,7 +125,7 @@ export async function createStaticMetadataFromRoute( ...@@ -125,7 +125,7 @@ export async function createStaticMetadataFromRoute(
}) })
} }
// Intentially make these serial to reuse directory access cache. // Intentionally make these serial to reuse directory access cache.
await collectIconModuleIfExists('icon') await collectIconModuleIfExists('icon')
await collectIconModuleIfExists('apple') await collectIconModuleIfExists('apple')
await collectIconModuleIfExists('openGraph') await collectIconModuleIfExists('openGraph')
......
import type { webpack } from 'next/dist/compiled/webpack/webpack'
import { import {
BARREL_OPTIMIZATION_PREFIX, BARREL_OPTIMIZATION_PREFIX,
RSC_MODULE_TYPES, RSC_MODULE_TYPES,
...@@ -5,39 +6,59 @@ import { ...@@ -5,39 +6,59 @@ import {
import { getModuleBuildInfo } from './get-module-build-info' import { getModuleBuildInfo } from './get-module-build-info'
import { regexCSS } from './utils' import { regexCSS } from './utils'
export type ClientComponentImports = string[] /**
* { [client import path]: [exported names] }
*/
export type ClientComponentImports = Record<string, Set<string>>
export type CssImports = Record<string, string[]> export type CssImports = Record<string, string[]>
export type NextFlightClientEntryLoaderOptions = { export type NextFlightClientEntryLoaderOptions = {
modules: ClientComponentImports modules: string[] | string
/** This is transmitted as a string to `getOptions` */ /** This is transmitted as a string to `getOptions` */
server: boolean | 'true' | 'false' server: boolean | 'true' | 'false'
} }
export default function transformSource(this: any) { export type FlightClientEntryModuleItem = {
let { modules, server }: NextFlightClientEntryLoaderOptions = // module path
this.getOptions() request: string
// imported identifiers
ids: string[]
}
export default function transformSource(
this: webpack.LoaderContext<NextFlightClientEntryLoaderOptions>
) {
let { modules, server } = this.getOptions()
const isServer = server === 'true' const isServer = server === 'true'
if (!Array.isArray(modules)) { if (!Array.isArray(modules)) {
modules = modules ? [modules] : [] modules = modules ? [modules] : []
} }
const requests = modules as string[] const code = modules
const code = requests .map((x) => JSON.parse(x) as FlightClientEntryModuleItem)
// Filter out CSS files in the SSR compilation // Filter out CSS files in the SSR compilation
.filter((request) => (isServer ? !regexCSS.test(request) : true)) .filter(({ request }) => (isServer ? !regexCSS.test(request) : true))
.map( .map(({ request, ids }: FlightClientEntryModuleItem) => {
(request) => const importPath = JSON.stringify(
`import(/* webpackMode: "eager" */ ${JSON.stringify( request.startsWith(BARREL_OPTIMIZATION_PREFIX)
request.startsWith(BARREL_OPTIMIZATION_PREFIX) ? request.replace(':', '!=!')
? request.replace(':', '!=!') : request
: request )
)})`
) // When we cannot determine the export names, we use eager mode to include the whole module.
// Otherwise, we use eager mode with webpackExports to only include the necessary exports.
if (ids.length === 0) {
return `import(/* webpackMode: "eager" */ ${importPath});\n`
} else {
return `import(/* webpackMode: "eager", webpackExports: ${JSON.stringify(
ids
)} */ ${importPath});\n`
}
})
.join(';\n') .join(';\n')
const buildInfo = getModuleBuildInfo(this._module) const buildInfo = getModuleBuildInfo(this._module!)
buildInfo.rsc = { buildInfo.rsc = {
type: RSC_MODULE_TYPES.client, type: RSC_MODULE_TYPES.client,
......
...@@ -99,9 +99,10 @@ const __default__ = proxy.default; ...@@ -99,9 +99,10 @@ const __default__ = proxy.default;
if (ref === '') { if (ref === '') {
esmSource += `\nexports[''] = createProxy(String.raw\`${resourceKey}#\`);` esmSource += `\nexports[''] = createProxy(String.raw\`${resourceKey}#\`);`
} else if (ref === 'default') { } else if (ref === 'default') {
esmSource += ` esmSource += `\
export { __esModule, $$typeof }; export { __esModule, $$typeof };
export default __default__;` export default createProxy(String.raw\`${resourceKey}#default\`);
`
} else { } else {
esmSource += ` esmSource += `
const e${cnt} = createProxy(String.raw\`${resourceKey}#${ref}\`); const e${cnt} = createProxy(String.raw\`${resourceKey}#${ref}\`);
......
...@@ -97,6 +97,7 @@ export const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS = 'polyfills' ...@@ -97,6 +97,7 @@ export const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS = 'polyfills'
export const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = Symbol( export const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = Symbol(
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS CLIENT_STATIC_FILES_RUNTIME_POLYFILLS
) )
export const DEFAULT_RUNTIME_WEBPACK = 'webpack-runtime'
export const EDGE_RUNTIME_WEBPACK = 'edge-runtime-webpack' export const EDGE_RUNTIME_WEBPACK = 'edge-runtime-webpack'
export const STATIC_PROPS_ID = '__N_SSG' export const STATIC_PROPS_ID = '__N_SSG'
export const SERVER_PROPS_ID = '__N_SSP' export const SERVER_PROPS_ID = '__N_SSP'
......
'use client' 'use client'
// TODO-APP: support typing for useSelectedLayoutSegment
// @ts-ignore
import { useSelectedLayoutSegments } from 'next/navigation' import { useSelectedLayoutSegments } from 'next/navigation'
export default function Layout({ children }: { children: React.ReactNode }) { export default function Layout({ children }: { children: React.ReactNode }) {
......
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export const dynamic = 'forced-dynamic'
'use client'
export function ImportedComp() {
return <div>client-comp-imported</div>
}
export function UnusedComp() {
return <div>client-comp-unused</div>
}
export default function DefaultComp() {
return <div>client-comp-default</div>
}
import { ImportedComp } from './client'
export default function Page() {
return <ImportedComp />
}
import { ClientBar } from 'esm-client-module'
export default function Page() {
return <ClientBar />
}
import fs from 'fs'
import { createNextDescribe } from 'e2e-utils'
import { join } from 'path'
createNextDescribe(
'app-dir client-components-tree-shaking',
{
files: __dirname,
skipDeployment: true,
},
({ next }) => {
it('should only include imported relative components in browser bundle with direct imports', async () => {
const clientChunksDir = join(
next.testDir,
'.next',
'static',
'chunks',
'app',
'relative-dep'
)
const staticChunksDirents = fs.readdirSync(clientChunksDir, {
withFileTypes: true,
})
const chunkContents = staticChunksDirents
.filter((dirent) => dirent.isFile())
.map((chunkDirent) =>
fs.readFileSync(join(chunkDirent.path, chunkDirent.name), 'utf8')
)
expect(
chunkContents.some((content) =>
content.includes('client-comp-imported')
)
).toBe(true)
expect(
chunkContents.every((content) => content.includes('client-comp-unused'))
).toBe(false)
expect(
chunkContents.every((content) =>
content.includes('client-comp-default')
)
).toBe(false)
})
it('should only include imported components 3rd party package in browser bundle with direct imports', async () => {
const clientChunksDir = join(
next.testDir,
'.next',
'static',
'chunks',
'app',
'third-party-dep'
)
const staticChunksDirents = fs.readdirSync(clientChunksDir, {
withFileTypes: true,
})
const chunkContents = staticChunksDirents
.filter((dirent) => dirent.isFile())
.map((chunkDirent) =>
fs.readFileSync(join(chunkDirent.path, chunkDirent.name), 'utf8')
)
expect(
chunkContents.some((content) => content.includes('client-dep-bar:esm'))
).toBe(true)
expect(
chunkContents.every((content) => content.includes('client-dep-foo:esm'))
).toBe(false)
expect(
chunkContents.every((content) =>
content.includes('client-dep-default:esm')
)
).toBe(false)
})
}
)
'use client'
const ClientFoo = () => 'client-dep-foo:esm'
const ClientBar = () => 'client-dep-bar:esm'
const ClientDefault = () => 'client-dep-default:esm'
export { ClientFoo, ClientBar }
export default ClientDefault
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment