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

[edge] favor browser exports for edge compiler #38319

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 7 additions & 5 deletions packages/next/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,12 @@ export default async function getBaseWebpackConfig(
const reactDir = dirname(require.resolve('react/package.json'))
const reactDomDir = dirname(require.resolve('react-dom/package.json'))

const mainFieldsPerCompiler: Record<typeof compilerType, string[]> = {
server: ['main', 'module'],
client: ['browser', 'module', 'main'],
'edge-server': ['browser', 'module', 'main'],
}

const resolveConfig = {
// Disable .mjs for node_modules bundling
extensions: isNodeServer
Expand Down Expand Up @@ -700,11 +706,7 @@ export default async function getBaseWebpackConfig(
},
}
: undefined),
mainFields: isClient
? ['browser', 'module', 'main']
: isEdgeServer
? ['module', 'main']
: ['main', 'module'],
mainFields: mainFieldsPerCompiler[compilerType],
plugins: [],
}

Expand Down
48 changes: 48 additions & 0 deletions test/e2e/edge-compiler-module-exports-preference/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { createNext } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { fetchViaHTTP } from 'next-test-utils'

describe('Edge compiler module exports preference', () => {
let next: NextInstance

beforeAll(async () => {
next = await createNext({
files: {
'pages/index.js': `
export default function Page() {
return <p>hello world</p>
}
`,
'middleware.js': `
import { NextResponse } from 'next/server';
import lib from 'my-lib';

export default (req) => {
return NextResponse.next({
headers: {
'x-imported': lib
}
})
}
`,
'node_modules/my-lib/package.json': JSON.stringify({
name: 'my-lib',
version: '1.0.0',
main: 'index.js',
browser: 'browser.js',
}),
'node_modules/my-lib/index.js': `module.exports = "Node.js"`,
'node_modules/my-lib/browser.js': `module.exports = "Browser"`,
},
dependencies: {},
})
})
afterAll(() => next.destroy())

it('favors the browser export', async () => {
const response = await fetchViaHTTP(next.url, '/')
expect(Object.fromEntries(response.headers)).toMatchObject({
'x-imported': 'Browser',
})
})
})