Skip to content

Commit

Permalink
use dependOn to optimize chunks
Browse files Browse the repository at this point in the history
disable vendor splitting for main and _app chunks
  • Loading branch information
sokra committed Apr 30, 2021
1 parent 67206a6 commit 1aa3207
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
10 changes: 9 additions & 1 deletion packages/next/build/entries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,15 @@ export function createPagesMapping(
}

export type WebpackEntrypoints = {
[bundle: string]: string | string[]
// for backward-compat
'main.js': string | string[]
[bundle: string]:
| string
| string[]
| {
import: string | string[]
dependOn: string | string[]
}
}

type Entrypoints = {
Expand Down
34 changes: 32 additions & 2 deletions packages/next/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,9 @@ export default async function getBaseWebpackConfig(
},
},
prodGranular: {
chunks: 'all',
// Keep main and _app chunks unsplitted in webpack 5
// as we don't need a separate vendor chunk from that.
chunks: (chunk) => !/^(main|pages\/_app)$/.test(chunk.name),
cacheGroups: {
framework: {
chunks: 'all',
Expand Down Expand Up @@ -851,6 +853,7 @@ export default async function getBaseWebpackConfig(
setImmediate: false,
},
// Kept as function to be backwards compatible
// @ts-ignore TODO webpack 5 typings needed
entry: async () => {
return {
...(clientEntries ? clientEntries : {}),
Expand Down Expand Up @@ -1601,9 +1604,12 @@ export default async function getBaseWebpackConfig(
}

// Backwards compat for `main.js` entry key
// and setup of dependencies between entries
// we can't do that in the initial entry for
// backward-compat reasons
const originalEntry: any = webpackConfig.entry
if (typeof originalEntry !== 'undefined') {
webpackConfig.entry = async () => {
const updatedEntry = async () => {
const entry: WebpackEntrypoints =
typeof originalEntry === 'function'
? await originalEntry()
Expand All @@ -1620,8 +1626,32 @@ export default async function getBaseWebpackConfig(
}
delete entry['main.js']

if (isWebpack5 && !isServer) {
for (const name of Object.keys(entry)) {
if (name === 'main') continue
const dependOn =
name.startsWith('pages/') && name !== 'pages/_app'
? 'pages/_app'
: 'main'
const old = entry[name]
if (typeof old === 'object' && !Array.isArray(old)) {
entry[name] = {
dependOn,
...old,
}
} else {
entry[name] = {
import: old,
dependOn,
}
}
}
}

return entry
}
// @ts-ignore webpack 5 typings needed
webpackConfig.entry = updatedEntry
}

if (!dev) {
Expand Down

0 comments on commit 1aa3207

Please sign in to comment.