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

Add support for "type": "module" in package.json #33637

Merged
merged 10 commits into from Feb 15, 2022
7 changes: 7 additions & 0 deletions packages/next/build/index.ts
Expand Up @@ -529,6 +529,13 @@ export default async function build(
await recursiveDelete(distDir, /^cache/)
}

// Ensure commonjs handling is used for files in the distDir (generally .next)
// Files outside of the distDir can be "type": "module"
await promises.writeFile(
path.join(config.distDir, 'package.json'),
'{"type": "commonjs"}'
)

// We need to write the manifest with rewrites before build
// so serverless can import the manifest
await nextBuildSpan
Expand Down
10 changes: 10 additions & 0 deletions packages/next/server/dev/hot-reloader.ts
Expand Up @@ -41,6 +41,7 @@ import { DecodeError } from '../../shared/lib/utils'
import { Span, trace } from '../../trace'
import { getProperError } from '../../lib/is-error'
import ws from 'next/dist/compiled/ws'
import { promises as fs } from 'fs'

const wsServer = new ws.Server({ noServer: true })

Expand Down Expand Up @@ -431,6 +432,15 @@ export default class HotReloader {
startSpan.stop() // Stop immediately to create an artificial parent span

await this.clean(startSpan)
// Ensure distDir exists before writing package.json
await fs.mkdir(this.config.distDir, { recursive: true })

// Ensure commonjs handling is used for files in the distDir (generally .next)
// Files outside of the distDir can be "type": "module"
await fs.writeFile(
join(this.config.distDir, 'package.json'),
'{"type": "commonjs"}'
)

const configs = await this.getWebpackConfig(startSpan)

Expand Down
42 changes: 42 additions & 0 deletions test/e2e/type-module-interop/index.test.ts
@@ -0,0 +1,42 @@
import { createNext } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { hasRedbox, renderViaHTTP } from 'next-test-utils'
import webdriver from 'next-webdriver'

describe('Type module interop', () => {
let next: NextInstance

beforeAll(async () => {
next = await createNext({
files: {
'pages/index.js': `
export default function Page() {
return <p>hello world</p>
}
`,
},
dependencies: {},
})
const contents = await next.readFile('package.json')
const pkg = JSON.parse(contents)
await next.patchFile(
'package.json',
JSON.stringify({
...pkg,
type: 'module',
})
)
})
afterAll(() => next.destroy())

it('should render server-side', async () => {
const html = await renderViaHTTP(next.url, '/')
expect(html).toContain('hello world')
})

it('should render client-side', async () => {
const browser = await webdriver(next.url, '/')
expect(await hasRedbox(browser)).toBe(false)
await browser.close()
})
})