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

Externalize node binary modules for app router (#70646)

backport #70330 
Fixes #69912

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 0ffea650
...@@ -1192,6 +1192,8 @@ export default async function getBaseWebpackConfig( ...@@ -1192,6 +1192,8 @@ export default async function getBaseWebpackConfig(
'next-metadata-route-loader', 'next-metadata-route-loader',
'modularize-import-loader', 'modularize-import-loader',
'next-barrel-loader', 'next-barrel-loader',
'next-server-binary-loader',
'next-error-browser-binary-loader',
].reduce((alias, loader) => { ].reduce((alias, loader) => {
// using multiple aliases to replace `resolveLoader.modules` // using multiple aliases to replace `resolveLoader.modules`
alias[loader] = path.join(__dirname, 'webpack', 'loaders', loader) alias[loader] = path.join(__dirname, 'webpack', 'loaders', loader)
...@@ -1276,6 +1278,17 @@ export default async function getBaseWebpackConfig( ...@@ -1276,6 +1278,17 @@ export default async function getBaseWebpackConfig(
or: WEBPACK_LAYERS.GROUP.nonClientServerTarget, or: WEBPACK_LAYERS.GROUP.nonClientServerTarget,
}, },
}, },
{
test: /[\\/].*?\.node$/,
loader: isNodeServer
? 'next-server-binary-loader'
: 'next-error-browser-binary-loader',
// On server side bundling, only apply to app router, do not apply to pages router;
// On client side or edge runtime bundling, always error.
...(isNodeServer && {
issuerLayer: isWebpackAppLayer,
}),
},
...(hasAppDir ...(hasAppDir
? [ ? [
{ {
......
import type { webpack } from 'next/dist/compiled/webpack/webpack'
export default function nextErrorBrowserBinaryLoader(
this: webpack.LoaderContext<any>
) {
const { resourcePath, rootContext } = this
const relativePath = resourcePath.slice(rootContext.length + 1)
throw new Error(
`Node.js binary module ./${relativePath} is not supported in the browser. Please only use the module on server side`
)
}
import type { webpack } from 'next/dist/compiled/webpack/webpack'
import path from 'path'
export default function nextErrorBrowserBinaryLoader(
this: webpack.LoaderContext<any>
) {
let relativePath = path.relative(this.rootContext, this.resourcePath)
if (!relativePath.startsWith('.')) {
relativePath = './' + relativePath
}
return `module.exports = __non_webpack_require__(${JSON.stringify(
relativePath
)})`
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import { foo } from 'foo-browser-import-binary'
export default function Page() {
return <p>{foo()}</p>
}
import { nextTestSetup } from 'e2e-utils'
import {
hasRedbox,
getRedboxDescription,
getRedboxSource,
} from 'next-test-utils'
;(process.env.TURBOPACK ? describe.skip : describe)(
'externalize-node-binary-browser-error',
() => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should error when import node binary on browser side', async () => {
const browser = await next.browser('/')
await hasRedbox(browser)
const redbox = {
description: await getRedboxDescription(browser),
source: await getRedboxSource(browser),
}
expect(redbox.description).toBe('Failed to compile')
expect(redbox.source).toMatchInlineSnapshot(`
"./node_modules/foo-browser-import-binary/binary.node
Error: Node.js binary module ./node_modules/foo-browser-import-binary/binary.node is not supported in the browser. Please only use the module on server side"
`)
})
}
)
exports.foo = function () {
return 'I am foo'
}
exports.bar = function () {
if (typeof window !== 'undefined') {
// This will be bundled on server side
require('./binary.node')
}
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { foo } from 'foo'
export default function Page() {
return <p>{foo()}</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('externalize-node-binary', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should render correctly when node_modules require node binary module', async () => {
const { status } = await next.fetch('/')
expect(status).toBe(200)
const browser = await next.browser('/')
expect(await browser.elementByCss('p').text()).toBe('I am foo')
})
})
�This-leading-char-will-trigger-Module parse failed: Unexpected character
exports.foo = function () {
return 'I am foo'
}
exports.bar = function () {
if (typeof window === 'undefined') {
require('./binary.node')
}
}
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