Fixed next-types-plugin causing Typescript errors when "type": "module" is set (#49027)

### What?

This fixes `next-types-plugin` causing Typescript to complain about CommonJS files importing ESM ones when `"type": "module"` is set but `experimental.typedRoutes` is not enabled.

### How?

Always create a `.next/types/package.json` with `"type": "module"` instead of only doing so when `experimental.typedRoutes` is enabled.

Fixes #49004
This commit is contained in:
Ngô Đức Anh 2023-05-01 23:19:05 +07:00 committed by GitHub
parent 2343610fdf
commit 2d800df099
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -588,11 +588,13 @@ export class NextTypesPlugin {
appTypesBasePath, appTypesBasePath,
relativePathToApp.replace(/\.(js|jsx|ts|tsx|mjs)$/, '.ts') relativePathToApp.replace(/\.(js|jsx|ts|tsx|mjs)$/, '.ts')
) )
const relativeImportPath = path const relativeImportPath = normalizePathSep(
path
.join(this.getRelativePathFromAppTypesDir(relativePathToApp)) .join(this.getRelativePathFromAppTypesDir(relativePathToApp))
.replace(/\.(js|jsx|ts|tsx|mjs)$/, '') .replace(/\.(js|jsx|ts|tsx|mjs)$/, '')
.replace(/\\/g, '/') )
const assetPath = assetDirRelative + '/' + normalizePathSep(typePath)
const assetPath = path.join(assetDirRelative, typePath)
if (IS_LAYOUT) { if (IS_LAYOUT) {
const slots = await collectNamedSlots(mod.resource) const slots = await collectNamedSlots(mod.resource)
@ -673,6 +675,17 @@ export class NextTypesPlugin {
await Promise.all(promises) await Promise.all(promises)
// Support `"moduleResolution": "Node16" | "NodeNext"` with `"type": "module"`
const packageJsonAssetPath = path.join(
assetDirRelative,
'types/package.json'
)
assets[packageJsonAssetPath] = new sources.RawSource(
'{"type": "module"}'
) as unknown as webpack.sources.RawSource
if (this.typedRoutes) { if (this.typedRoutes) {
if (this.dev && !this.isEdgeServer) { if (this.dev && !this.isEdgeServer) {
devPageFiles.forEach((file) => { devPageFiles.forEach((file) => {
@ -680,17 +693,8 @@ export class NextTypesPlugin {
}) })
} }
// Support tsconfig values for "moduleResolution": "Node16" or "NodeNext" const linkAssetPath = path.join(assetDirRelative, 'types/link.d.ts')
const packageJsonTypePath = path.join('types', 'package.json')
const packageJsonAssetPath =
assetDirRelative + '/' + normalizePathSep(packageJsonTypePath)
assets[packageJsonAssetPath] = new sources.RawSource(
'{"type": "module"}'
) as unknown as webpack.sources.RawSource
const linkTypePath = path.join('types', 'link.d.ts')
const linkAssetPath =
assetDirRelative + '/' + normalizePathSep(linkTypePath)
assets[linkAssetPath] = new sources.RawSource( assets[linkAssetPath] = new sources.RawSource(
createRouteDefinitions() createRouteDefinitions()
) as unknown as webpack.sources.RawSource ) as unknown as webpack.sources.RawSource