Unverified Commit b6b79333 authored by teobler's avatar teobler Committed by GitHub

fix: generate next-env.d.ts file during next lint command (#46249)

fixes #46104

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

---------
Co-authored-by: 's avatarWyatt Johnson <accounts+github@wyattjoh.ca>
parent 18dc09bf
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
/// <reference types="next/navigation-types/navigation" />
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information. // see https://nextjs.org/docs/basic-features/typescript for more information.
...@@ -18,7 +18,4 @@ declare module 'next/navigation' { ...@@ -18,7 +18,4 @@ declare module 'next/navigation' {
* router is not ready. * router is not ready.
*/ */
export function usePathname(): string | null export function usePathname(): string | null
// Re-export the types for next/navigation.
export * from 'next/dist/client/components/navigation'
} }
import type { ReadonlyURLSearchParams } from 'next/navigation'
declare module 'next/navigation' {
/**
* Get a read-only URLSearchParams object. For example searchParams.get('foo') would return 'bar' when ?foo=bar
* Learn more about URLSearchParams here: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
*/
export function useSearchParams(): ReadonlyURLSearchParams
/**
* Get the current pathname. For example, if the URL is
* https://example.com/foo?bar=baz, the pathname would be /foo.
*/
export function usePathname(): string
// Re-export the types for next/navigation.
export * from 'next/dist/client/components/navigation'
}
...@@ -18,6 +18,8 @@ import { eventLintCheckCompleted } from '../telemetry/events' ...@@ -18,6 +18,8 @@ import { eventLintCheckCompleted } from '../telemetry/events'
import { CompileError } from '../lib/compile-error' import { CompileError } from '../lib/compile-error'
import isError from '../lib/is-error' import isError from '../lib/is-error'
import { getProjectDir } from '../lib/get-project-dir' import { getProjectDir } from '../lib/get-project-dir'
import { findPagesDir } from '../lib/find-pages-dir'
import { verifyTypeScriptSetup } from '../lib/verifyTypeScriptSetup'
const eslintOptions = (args: arg.Spec, defaultCacheLocation: string) => ({ const eslintOptions = (args: arg.Spec, defaultCacheLocation: string) => ({
overrideConfigFile: args['--config'] || null, overrideConfigFile: args['--config'] || null,
...@@ -196,6 +198,21 @@ const nextLint: CliCommand = async (argv) => { ...@@ -196,6 +198,21 @@ const nextLint: CliCommand = async (argv) => {
const distDir = join(baseDir, nextConfig.distDir) const distDir = join(baseDir, nextConfig.distDir)
const defaultCacheLocation = join(distDir, 'cache', 'eslint/') const defaultCacheLocation = join(distDir, 'cache', 'eslint/')
const hasAppDir = !!nextConfig.experimental.appDir const hasAppDir = !!nextConfig.experimental.appDir
const { pagesDir, appDir } = findPagesDir(
baseDir,
!!nextConfig.experimental.appDir
)
await verifyTypeScriptSetup({
dir: baseDir,
distDir,
intentDirs: [pagesDir, appDir].filter(Boolean) as string[],
typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath,
disableStaticImages: nextConfig.images.disableStaticImages,
isAppDirEnabled: !!appDir,
hasPagesDir: !!pagesDir,
})
runLintCheck(baseDir, pathsToLint, hasAppDir, { runLintCheck(baseDir, pathsToLint, hasAppDir, {
lintDuringBuild: false, lintDuringBuild: false,
......
...@@ -67,13 +67,14 @@ export class ReadonlyURLSearchParams { ...@@ -67,13 +67,14 @@ export class ReadonlyURLSearchParams {
/** /**
* Get a read-only URLSearchParams object. For example searchParams.get('foo') would return 'bar' when ?foo=bar * Get a read-only URLSearchParams object. For example searchParams.get('foo') would return 'bar' when ?foo=bar
* Learn more about URLSearchParams here: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams * Learn more about URLSearchParams here: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
*
* @internal - re-exported in `next-env.d.ts`.
*/ */
export function useSearchParams(): ReadonlyURLSearchParams | null { export function useSearchParams(): ReadonlyURLSearchParams {
clientHookInServerComponentError('useSearchParams') clientHookInServerComponentError('useSearchParams')
const searchParams = useContext(SearchParamsContext) const searchParams = useContext(SearchParamsContext)
// In the case where this is `null`, the compat types added in
// `next-env.d.ts` will add a new overload that changes the return type to
// include `null`.
const readonlySearchParams = useMemo(() => { const readonlySearchParams = useMemo(() => {
if (!searchParams) { if (!searchParams) {
// When the router is not ready in pages, we won't have the search params // When the router is not ready in pages, we won't have the search params
...@@ -82,7 +83,7 @@ export function useSearchParams(): ReadonlyURLSearchParams | null { ...@@ -82,7 +83,7 @@ export function useSearchParams(): ReadonlyURLSearchParams | null {
} }
return new ReadonlyURLSearchParams(searchParams) return new ReadonlyURLSearchParams(searchParams)
}, [searchParams]) }, [searchParams]) as ReadonlyURLSearchParams
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
// AsyncLocalStorage should not be included in the client bundle. // AsyncLocalStorage should not be included in the client bundle.
...@@ -99,12 +100,12 @@ export function useSearchParams(): ReadonlyURLSearchParams | null { ...@@ -99,12 +100,12 @@ export function useSearchParams(): ReadonlyURLSearchParams | null {
/** /**
* Get the current pathname. For example usePathname() on /dashboard?foo=bar would return "/dashboard" * Get the current pathname. For example usePathname() on /dashboard?foo=bar would return "/dashboard"
*
* @internal - re-exported in `next-env.d.ts`.
*/ */
export function usePathname(): string | null { export function usePathname(): string {
clientHookInServerComponentError('usePathname') clientHookInServerComponentError('usePathname')
return useContext(PathnameContext) // In the case where this is `null`, the compat types added in `next-env.d.ts`
// will add a new overload that changes the return type to include `null`.
return useContext(PathnameContext) as string
} }
// TODO-APP: getting all params when client-side navigating is non-trivial as it does not have route matchers so this might have to be a server context instead. // TODO-APP: getting all params when client-side navigating is non-trivial as it does not have route matchers so this might have to be a server context instead.
......
...@@ -49,16 +49,10 @@ export async function writeAppTypeDeclarations({ ...@@ -49,16 +49,10 @@ export async function writeAppTypeDeclarations({
directives.push('/// <reference types="next/image-types/global" />') directives.push('/// <reference types="next/image-types/global" />')
} }
if (isAppDirEnabled) { if (isAppDirEnabled && hasPagesDir) {
if (hasPagesDir) { directives.push(
directives.push( '/// <reference types="next/navigation-types/compat/navigation" />'
'/// <reference types="next/navigation-types/compat/navigation" />' )
)
} else {
directives.push(
'/// <reference types="next/navigation-types/navigation" />'
)
}
} }
// Push the notice in. // Push the notice in.
......
...@@ -4,7 +4,7 @@ import os from 'os' ...@@ -4,7 +4,7 @@ import os from 'os'
import { join } from 'path' import { join } from 'path'
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
import { nextBuild, nextLint, File } from 'next-test-utils' import { File, nextBuild, nextLint } from 'next-test-utils'
const dirFirstTimeSetup = join(__dirname, '../first-time-setup') const dirFirstTimeSetup = join(__dirname, '../first-time-setup')
const dirCustomConfig = join(__dirname, '../custom-config') const dirCustomConfig = join(__dirname, '../custom-config')
...@@ -37,6 +37,7 @@ const dirEslintCache = join(__dirname, '../eslint-cache') ...@@ -37,6 +37,7 @@ const dirEslintCache = join(__dirname, '../eslint-cache')
const dirEslintCacheCustomDir = join(__dirname, '../eslint-cache-custom-dir') const dirEslintCacheCustomDir = join(__dirname, '../eslint-cache-custom-dir')
const dirFileLinting = join(__dirname, '../file-linting') const dirFileLinting = join(__dirname, '../file-linting')
const mjsCjsLinting = join(__dirname, '../mjs-cjs-linting') const mjsCjsLinting = join(__dirname, '../mjs-cjs-linting')
const dirTypescript = join(__dirname, '../with-typescript')
describe('ESLint', () => { describe('ESLint', () => {
describe('Next Build', () => { describe('Next Build', () => {
...@@ -353,6 +354,35 @@ describe('ESLint', () => { ...@@ -353,6 +354,35 @@ describe('ESLint', () => {
}) })
}) })
test('should generate next-env.d.ts before lint command', async () => {
await nextLint(dirTypescript, [], {
stdout: true,
stderr: true,
})
const files = await fs.readdir(dirTypescript)
expect(files).toContain('next-env.d.ts')
})
for (const { dir } of [
{ dir: dirEmptyDirectory },
{ dir: dirIgnoreDuringBuilds },
{ dir: dirCustomDirectories },
{ dir: dirConfigInPackageJson },
]) {
test('should not generate next-env.d.ts without typescript', async () => {
await nextLint(dir, [], {
stdout: true,
stderr: true,
})
const files = await fs.readdir(dir)
expect(files).not.toContain('next-env.d.ts')
})
}
test('shows warnings and errors', async () => { test('shows warnings and errors', async () => {
const { stdout, stderr } = await nextLint(dirCustomConfig, [], { const { stdout, stderr } = await nextLint(dirCustomConfig, [], {
stdout: true, stdout: true,
......
{
"extends": "next",
"root": true
}
import React from 'react'
const Home = () => (
<div>
<p>Home</p>
</div>
)
export default Home
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
...@@ -95,8 +95,8 @@ describe('find config', () => { ...@@ -95,8 +95,8 @@ describe('find config', () => {
isAppDirEnabled: true, isAppDirEnabled: true,
}) })
await expect(fs.readFile(declarationFile, 'utf8')).resolves.toContain( await expect(fs.readFile(declarationFile, 'utf8')).resolves.not.toContain(
'next/navigation-types/navigation' 'next/navigation-types/compat/navigation'
) )
await writeAppTypeDeclarations({ await writeAppTypeDeclarations({
......
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