rsnext/packages/next/server.js
Jiachi Liu 4aa5e9cad2
Fix next/server api alias for ESM pkg (#61721)
### What & Why

We have a modularize imports config for `next/server` before, which will
transform the `next/server` imports to directly import from the actual
file, for instance: `import { NextRequest } from 'next/server'` will
become `import { NextRequest } from
'next/dist/server/web/exports/next-request'`, where the NextRequest is
exported as default export. This is fine in most case until you're using
a ESM pkg, then it will be resolved as `{ default: NextRequest }`
according to the spec. Since it's a ESM import to a CJS module in
`next/dist`.

Since we already have the ESM alias introduced in #59852 , this can
handle the case more properly.

### How

Remove the modularize imports config for `next/server`, use the ESM api
alias instead.

Migrate the cjs optimizer tests from middleware to a separate endpoint
`/cjs/server`. As now ESM imports for next/server are not going to get
tree-shaken in dev, but since we don't have image response there it's
still fine.

Closes NEXT-2376
Closes NEXT-2374
2024-02-06 16:59:24 +00:00

26 lines
1.1 KiB
JavaScript

const serverExports = {
NextRequest: require('next/dist/server/web/spec-extension/request')
.NextRequest,
NextResponse: require('next/dist/server/web/spec-extension/response')
.NextResponse,
ImageResponse: require('next/dist/server/web/spec-extension/image-response')
.ImageResponse,
userAgentFromString: require('next/dist/server/web/spec-extension/user-agent')
.userAgentFromString,
userAgent: require('next/dist/server/web/spec-extension/user-agent')
.userAgent,
URLPattern: require('next/dist/server/web/spec-extension/url-pattern')
.URLPattern,
}
// https://nodejs.org/api/esm.html#commonjs-namespaces
// When importing CommonJS modules, the module.exports object is provided as the default export
module.exports = serverExports
// make import { xxx } from 'next/server' work
exports.NextRequest = serverExports.NextRequest
exports.NextResponse = serverExports.NextResponse
exports.ImageResponse = serverExports.ImageResponse
exports.userAgentFromString = serverExports.userAgentFromString
exports.userAgent = serverExports.userAgent
exports.URLPattern = serverExports.URLPattern