Unverified Commit da6f271d authored by LongYinan's avatar LongYinan Committed by GitHub

Interpolate module.exports as default import (#36082)



fixes https://github.com/vercel/next.js/issues/34412

## Bug

- [x] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`
parent a9d6d9f7
...@@ -10,6 +10,8 @@ import { promisify } from 'util' ...@@ -10,6 +10,8 @@ import { promisify } from 'util'
import { parse } from '../../swc' import { parse } from '../../swc'
import { buildExports } from './utils' import { buildExports } from './utils'
const IS_NEXT_CLIENT_BUILT_IN = /[\\/]next[\\/](link|image)\.js$/
function addExportNames(names: string[], node: any) { function addExportNames(names: string[], node: any) {
if (!node) return if (!node) return
switch (node.type) { switch (node.type) {
...@@ -57,7 +59,7 @@ async function collectExports( ...@@ -57,7 +59,7 @@ async function collectExports(
const names: string[] = [] const names: string[] = []
// Next.js built-in client components // Next.js built-in client components
if (/[\\/]next[\\/](link|image)\.js$/.test(resourcePath)) { if (IS_NEXT_CLIENT_BUILT_IN.test(resourcePath)) {
names.push('default') names.push('default')
} }
...@@ -158,12 +160,14 @@ export default async function transformSource( ...@@ -158,12 +160,14 @@ export default async function transformSource(
const moduleRefDef = const moduleRefDef =
"const MODULE_REFERENCE = Symbol.for('react.module.reference');\n" "const MODULE_REFERENCE = Symbol.for('react.module.reference');\n"
const isNextClientBuiltIn = IS_NEXT_CLIENT_BUILT_IN.test(resourcePath)
const clientRefsExports = names.reduce((res: any, name) => { const clientRefsExports = names.reduce((res: any, name) => {
const moduleRef = const moduleRef =
'{ $$typeof: MODULE_REFERENCE, filepath: ' + '{ $$typeof: MODULE_REFERENCE, filepath: ' +
JSON.stringify(resourcePath) + JSON.stringify(resourcePath) +
', name: ' + ', name: ' +
JSON.stringify(name) + JSON.stringify(name === 'default' && isNextClientBuiltIn ? '' : name) +
' };\n' ' };\n'
res[name] = moduleRef res[name] = moduleRef
return res return res
......
...@@ -34,8 +34,12 @@ function isValidSeverity(severity: string): severity is Severity { ...@@ -34,8 +34,12 @@ function isValidSeverity(severity: string): severity is Severity {
} }
const requiredPackages = [ const requiredPackages = [
{ file: 'eslint', pkg: 'eslint' }, { file: 'eslint', pkg: 'eslint', exportsRestrict: false },
{ file: 'eslint-config-next', pkg: 'eslint-config-next' }, {
file: 'eslint-config-next',
pkg: 'eslint-config-next',
exportsRestrict: false,
},
] ]
async function cliPrompt() { async function cliPrompt() {
......
import { existsSync } from 'fs'
import { join, relative } from 'path'
export interface MissingDependency { export interface MissingDependency {
file: string file: string
pkg: string pkg: string
exportsRestrict: boolean
} }
export type NecessaryDependencies = { export type NecessaryDependencies = {
...@@ -15,7 +19,24 @@ export async function hasNecessaryDependencies( ...@@ -15,7 +19,24 @@ export async function hasNecessaryDependencies(
let resolutions = new Map<string, string>() let resolutions = new Map<string, string>()
const missingPackages = requiredPackages.filter((p) => { const missingPackages = requiredPackages.filter((p) => {
try { try {
resolutions.set(p.pkg, require.resolve(p.file, { paths: [baseDir] })) if (p.exportsRestrict) {
const pkgPath = require.resolve(`${p.pkg}/package.json`, {
paths: [baseDir],
})
const fileNameToVerify = relative(p.pkg, p.file)
if (fileNameToVerify) {
const fileToVerify = join(pkgPath, '..', fileNameToVerify)
if (existsSync(fileToVerify)) {
resolutions.set(p.pkg, join(pkgPath, '..'))
} else {
return true
}
} else {
resolutions.set(p.pkg, pkgPath)
}
} else {
resolutions.set(p.pkg, require.resolve(p.file, { paths: [baseDir] }))
}
return false return false
} catch (_) { } catch (_) {
return true return true
......
...@@ -61,7 +61,13 @@ export async function verifyPartytownSetup( ...@@ -61,7 +61,13 @@ export async function verifyPartytownSetup(
try { try {
const partytownDeps: NecessaryDependencies = await hasNecessaryDependencies( const partytownDeps: NecessaryDependencies = await hasNecessaryDependencies(
dir, dir,
[{ file: '@builder.io/partytown', pkg: '@builder.io/partytown' }] [
{
file: '@builder.io/partytown',
pkg: '@builder.io/partytown',
exportsRestrict: false,
},
]
) )
if (partytownDeps.missing?.length > 0) { if (partytownDeps.missing?.length > 0) {
......
...@@ -17,9 +17,17 @@ import { missingDepsError } from './typescript/missingDependencyError' ...@@ -17,9 +17,17 @@ import { missingDepsError } from './typescript/missingDependencyError'
import { NextConfigComplete } from '../server/config-shared' import { NextConfigComplete } from '../server/config-shared'
const requiredPackages = [ const requiredPackages = [
{ file: 'typescript', pkg: 'typescript' }, { file: 'typescript', pkg: 'typescript', exportsRestrict: false },
{ file: '@types/react/index.d.ts', pkg: '@types/react' }, {
{ file: '@types/node/index.d.ts', pkg: '@types/node' }, file: '@types/react/index.d.ts',
pkg: '@types/react',
exportsRestrict: true,
},
{
file: '@types/node/index.d.ts',
pkg: '@types/node',
exportsRestrict: false,
},
] ]
export async function verifyTypeScriptSetup( export async function verifyTypeScriptSetup(
......
...@@ -14,7 +14,11 @@ module.exports = function (task) { ...@@ -14,7 +14,11 @@ module.exports = function (task) {
function* ( function* (
file, file,
serverOrClient, serverOrClient,
{ stripExtension, keepImportAssertions = false } = {} {
stripExtension,
keepImportAssertions = false,
interopClientDefaultExport = false,
} = {}
) { ) {
// Don't compile .d.ts // Don't compile .d.ts
if (file.base.endsWith('.d.ts')) return if (file.base.endsWith('.d.ts')) return
...@@ -111,6 +115,15 @@ module.exports = function (task) { ...@@ -111,6 +115,15 @@ module.exports = function (task) {
} }
if (output.map) { if (output.map) {
if (interopClientDefaultExport) {
output.code += `
if (typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) {
Object.assign(exports.default, exports);
module.exports = exports.default;
}
`
}
const map = `${file.base}.map` const map = `${file.base}.map`
output.code += Buffer.from(`\n//# sourceMappingURL=${map}`) output.code += Buffer.from(`\n//# sourceMappingURL=${map}`)
......
...@@ -1826,7 +1826,7 @@ export async function nextbuild(task, opts) { ...@@ -1826,7 +1826,7 @@ export async function nextbuild(task, opts) {
export async function client(task, opts) { export async function client(task, opts) {
await task await task
.source(opts.src || 'client/**/*.+(js|ts|tsx)') .source(opts.src || 'client/**/*.+(js|ts|tsx)')
.swc('client', { dev: opts.dev }) .swc('client', { dev: opts.dev, interopClientDefaultExport: true })
.target('dist/client') .target('dist/client')
notify('Compiled client files') notify('Compiled client files')
} }
......
...@@ -11,8 +11,17 @@ describe('Type module interop', () => { ...@@ -11,8 +11,17 @@ describe('Type module interop', () => {
next = await createNext({ next = await createNext({
files: { files: {
'pages/index.js': ` 'pages/index.js': `
import Link from 'next/link'
export default function Page() { export default function Page() {
return <p>hello world</p> return (
<>
<p>hello world</p>
<Link href="/modules">
<a id="link-to-module">link to module</a>
</Link>
</>
)
} }
`, `,
'pages/modules.jsx': ` 'pages/modules.jsx': `
......
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