Skip to content

Commit

Permalink
Apply optimization to middleware when using babel (#51067)
Browse files Browse the repository at this point in the history
Like how we handled RSC loader transform before, we also apply swc
loader to middleware to make sure the imports optimization is applied so
og package won't be bundled

Fixes #50492
  • Loading branch information
huozhi committed Jun 9, 2023
1 parent 8045525 commit 2bc1061
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
9 changes: 8 additions & 1 deletion packages/next/src/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -899,7 +899,14 @@ export default async function getBaseWebpackConfig(
: []
const swcLoaderForMiddlewareLayer = useSWCLoader
? getSwcLoader({ hasServerComponents: false })
: getBabelLoader()
: // When using Babel, we will have to use SWC to do the optimization
// for middleware to tree shake the unused default optimized imports like "next/server".
// This will cause some performance overhead but
// acceptable as Babel will not be recommended.
[
getSwcLoader({ hasServerComponents: false, isServerLayer: false }),
getBabelLoader(),
]

// Loader for API routes needs to be differently configured as it shouldn't
// have RSC transpiler enabled, so syntax checks such as invalid imports won't
Expand Down
5 changes: 5 additions & 0 deletions test/e2e/app-dir/with-babel/middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { NextResponse } from 'next/server'

export async function middleware() {
return NextResponse.next()
}
10 changes: 9 additions & 1 deletion test/e2e/app-dir/with-babel/with-babel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,18 @@ createNextDescribe(
files: __dirname,
skipDeployment: true,
},
({ next }) => {
({ next, isNextStart }) => {
it('should support babel in app dir', async () => {
const $ = await next.render$('/')
expect($('h1').text()).toBe('hello')
})

if (isNextStart) {
it('should contain og package files in middleware', async () => {
const middleware = await next.readFile('.next/server/middleware.js')
// @vercel/og default font should be bundled
expect(middleware).not.toContain('noto-sans-v27-latin-regular.ttf')
})
}
}
)

0 comments on commit 2bc1061

Please sign in to comment.