Unverified Commit f126e722 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

[backport] Fix "type: module" in project dir when using standalone or adapters (#94050)

Backports [Fix "type: module" in project dir when using standalone or
adapters](https://github.com/vercel/next.js/pull/93612) to `next-16-2`.

<!-- NEXT_JS_LLM_PR -->
parent bda3e2aa
...@@ -118,9 +118,6 @@ impl Asset for ServerNftJsonAsset { ...@@ -118,9 +118,6 @@ impl Asset for ServerNftJsonAsset {
.try_join() .try_join()
.await?; .await?;
// A few hardcoded files (not recursive)
server_output_assets.push("./package.json".into());
let next_dir = get_next_package(this.project.project_path().owned().await?).await?; let next_dir = get_next_package(this.project.project_path().owned().await?).await?;
for ty in ["app-page", "pages"] { for ty in ["app-page", "pages"] {
let dir = next_dir.join(&format!("dist/server/route-modules/{ty}"))?; let dir = next_dir.join(&format!("dist/server/route-modules/{ty}"))?;
......
...@@ -1834,6 +1834,9 @@ export default async function build( ...@@ -1834,6 +1834,9 @@ export default async function build(
appDir: dir, appDir: dir,
relativeAppDir: path.relative(outputFileTracingRoot, dir), relativeAppDir: path.relative(outputFileTracingRoot, dir),
files: [ files: [
// distDir `{"type":"commonjs"}` boundary so `.next/server/**/*.js`
// is loaded as CJS when the user's project is "type": "module".
'package.json',
ROUTES_MANIFEST, ROUTES_MANIFEST,
path.relative(distDir, pagesManifestPath), path.relative(distDir, pagesManifestPath),
BUILD_MANIFEST, BUILD_MANIFEST,
......
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import fs from 'fs'
import path from 'path'
/** @type {import('next').NextAdapter } */
const myAdapter = {
name: 'package-boundary-test-adapter',
onBuildComplete: async (ctx) => {
// Capture every page output's assets so the test can assert the distDir
// package.json boundary marker is reachable from the page bundle's
// function root. Without this, Node walks up to the user's
// "type": "module" package.json and loads `.next/server/**/*.js` as ESM.
const pageAssets = {}
for (const output of [...ctx.outputs.pages, ...ctx.outputs.appPages]) {
pageAssets[output.id] = Object.keys(output.assets || {}).sort()
}
await fs.promises.writeFile(
path.join(ctx.distDir, 'adapter-page-assets.json'),
JSON.stringify(pageAssets, null, 2)
)
},
}
export default myAdapter
import Module from 'module'
const require = Module.createRequire(import.meta.url)
/** @type {import('next').NextConfig} */
const nextConfig = {
adapterPath: require.resolve('./my-adapter.mjs'),
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import { join } from 'path'
describe('distDir package.json commonjs boundary', () => {
const { next } = nextTestSetup({
files: __dirname,
// Use "type": "module" in the project package.json so the boundary file
// is what determines whether `.next/server/**/*.js` is loaded as CJS.
packageJson: {
type: 'module',
},
})
it('writes the distDir package.json with the commonjs boundary', async () => {
const distPackageJson = JSON.parse(
await next.readFile('.next/package.json')
)
expect(distPackageJson).toEqual({ type: 'commonjs' })
})
it('lists the distDir package.json in required-server-files.json', async () => {
const manifest = JSON.parse(
await next.readFile('.next/required-server-files.json')
)
// Adapters consume `requiredServerFiles.files` to seed the per-page
// shared assets. The boundary marker must be in this list because
// per-page nft traces do not include it.
expect(manifest.files).toContain(join('.next', 'package.json'))
})
it('includes the distDir package.json in every adapter page output assets', async () => {
// The adapter writes per-page asset keys to `.next/adapter-page-assets.json`
// during onBuildComplete. The fix in `build/index.ts` ensures the boundary
// is in `requiredServerFiles.files`, which `handleBuildComplete` then
// merges into every page output's `assets` map.
const pageAssets = JSON.parse(
await next.readFile('.next/adapter-page-assets.json')
)
const pageIds = Object.keys(pageAssets)
expect(pageIds.length).toBeGreaterThan(0)
const boundaryPath = join('.next', 'package.json')
for (const pageId of pageIds) {
expect(pageAssets[pageId]).toContain(boundaryPath)
}
})
})
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { join } from 'path' import { join } from 'path'
import fs from 'fs-extra' import fs from 'fs-extra'
import cheerio from 'cheerio'
import { import {
fetchViaHTTP, fetchViaHTTP,
findPort, findPort,
...@@ -22,6 +23,17 @@ describe('type-module', () => { ...@@ -22,6 +23,17 @@ describe('type-module', () => {
expect(fs.existsSync(join(standalonePath, 'package.json'))).toBe(true) expect(fs.existsSync(join(standalonePath, 'package.json'))).toBe(true)
// The distDir package.json acts as a commonjs boundary marker so that
// server bundles in `.next/server/**/*.js` are loaded as CJS even when
// the user's project has `"type": "module"`. Without this file, Node
// walks up to the project package.json and tries to load the server
// bundles as ESM, which fails at runtime.
const distPackageJsonPath = join(standalonePath, '.next', 'package.json')
expect(fs.existsSync(distPackageJsonPath)).toBe(true)
expect(JSON.parse(await fs.readFile(distPackageJsonPath, 'utf8'))).toEqual({
type: 'commonjs',
})
const serverFile = join(standalonePath, 'server.js') const serverFile = join(standalonePath, 'server.js')
const appPort = await findPort() const appPort = await findPort()
...@@ -32,8 +44,17 @@ describe('type-module', () => { ...@@ -32,8 +44,17 @@ describe('type-module', () => {
undefined, undefined,
{ cwd: next.testDir } { cwd: next.testDir }
) )
const res = await fetchViaHTTP(appPort, '/') const staticRes = await fetchViaHTTP(appPort, '/')
expect(await res.text()).toContain('hello world') expect(await staticRes.text()).toContain('hello world')
// Hitting a server-rendered page forces Node to actually load
// `.next/server/pages/dynamic.js` at runtime, which only succeeds when
// the distDir commonjs boundary is in place.
const dynamicRes = await fetchViaHTTP(appPort, '/dynamic')
expect(dynamicRes.status).toBe(200)
const $ = cheerio.load(await dynamicRes.text())
expect($('#content').text()).toBe('dynamic-rendered-at-runtime')
await killApp(server) await killApp(server)
}) })
}) })
export default function Dynamic({ now }) {
return <p id="content">dynamic-{now}</p>
}
export async function getServerSideProps() {
return { props: { now: 'rendered-at-runtime' } }
}
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