Unverified Commit 917a9acc authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update to only add image import types when enabled (#26485)

* Update to only add image import types when enabled

* add type check to test
parent 27d78a5d
...@@ -192,7 +192,13 @@ export default async function build( ...@@ -192,7 +192,13 @@ export default async function build(
const verifyResult = await nextBuildSpan const verifyResult = await nextBuildSpan
.traceChild('verify-typescript-setup') .traceChild('verify-typescript-setup')
.traceAsyncFn(() => .traceAsyncFn(() =>
verifyTypeScriptSetup(dir, pagesDir, !ignoreTypeScriptErrors, cacheDir) verifyTypeScriptSetup(
dir,
pagesDir,
!ignoreTypeScriptErrors,
!config.images.disableStaticImages,
cacheDir
)
) )
const typeCheckEnd = process.hrtime(typeCheckStart) const typeCheckEnd = process.hrtime(typeCheckStart)
......
// this file is conditionally added/removed to next-env.d.ts
// if the static image import handling is enabled
interface StaticImageData {
src: string
height: number
width: number
placeholder?: string
}
declare module '*.png' {
const content: StaticImageData
export default content
}
declare module '*.svg' {
/**
* Use `any` to avoid conflicts with
* `@svgr/webpack` plugin or
* `babel-plugin-inline-react-svg` plugin.
*/
const content: any
export default content
}
declare module '*.jpg' {
const content: StaticImageData
export default content
}
declare module '*.jpeg' {
const content: StaticImageData
export default content
}
declare module '*.gif' {
const content: StaticImageData
export default content
}
declare module '*.webp' {
const content: StaticImageData
export default content
}
declare module '*.ico' {
const content: StaticImageData
export default content
}
declare module '*.bmp' {
const content: StaticImageData
export default content
}
import { promises as fs } from 'fs' import { promises as fs } from 'fs'
import os from 'os' import os from 'os'
import path from 'path' import path from 'path'
import { fileExists } from '../file-exists'
export async function writeAppTypeDeclarations(baseDir: string): Promise<void> { export async function writeAppTypeDeclarations(
baseDir: string,
imageImportsEnabled: boolean
): Promise<void> {
// Reference `next` types // Reference `next` types
const appTypeDeclarations = path.join(baseDir, 'next-env.d.ts') const appTypeDeclarations = path.join(baseDir, 'next-env.d.ts')
const hasAppTypeDeclarations = await fileExists(appTypeDeclarations)
if (!hasAppTypeDeclarations) { await fs.writeFile(
await fs.writeFile( appTypeDeclarations,
appTypeDeclarations, '/// <reference types="next" />' +
'/// <reference types="next" />' + os.EOL +
os.EOL + '/// <reference types="next/types/global" />' +
'/// <reference types="next/types/global" />' + os.EOL +
os.EOL (imageImportsEnabled
) ? '/// <reference types="next/image-types/global" />' + os.EOL
} : '')
)
} }
...@@ -18,6 +18,7 @@ export async function verifyTypeScriptSetup( ...@@ -18,6 +18,7 @@ export async function verifyTypeScriptSetup(
dir: string, dir: string,
pagesDir: string, pagesDir: string,
typeCheckPreflight: boolean, typeCheckPreflight: boolean,
imageImportsEnabled: boolean,
cacheDir?: string cacheDir?: string
): Promise<{ result?: TypeCheckResult; version: string | null }> { ): Promise<{ result?: TypeCheckResult; version: string | null }> {
const tsConfigPath = path.join(dir, 'tsconfig.json') const tsConfigPath = path.join(dir, 'tsconfig.json')
...@@ -52,7 +53,7 @@ export async function verifyTypeScriptSetup( ...@@ -52,7 +53,7 @@ export async function verifyTypeScriptSetup(
await writeConfigurationDefaults(ts, tsConfigPath, firstTimeSetup) await writeConfigurationDefaults(ts, tsConfigPath, firstTimeSetup)
// Write out the necessary `next-env.d.ts` file to correctly register // Write out the necessary `next-env.d.ts` file to correctly register
// Next.js' types: // Next.js' types:
await writeAppTypeDeclarations(dir) await writeAppTypeDeclarations(dir, imageImportsEnabled)
let result let result
if (typeCheckPreflight) { if (typeCheckPreflight) {
......
...@@ -275,7 +275,12 @@ export default class DevServer extends Server { ...@@ -275,7 +275,12 @@ export default class DevServer extends Server {
} }
async prepare(): Promise<void> { async prepare(): Promise<void> {
await verifyTypeScriptSetup(this.dir, this.pagesDir!, false) await verifyTypeScriptSetup(
this.dir,
this.pagesDir!,
false,
!this.nextConfig.images.disableStaticImages
)
this.customRoutes = await loadCustomRoutes(this.nextConfig) this.customRoutes = await loadCustomRoutes(this.nextConfig)
......
...@@ -25,63 +25,3 @@ declare module '*.module.scss' { ...@@ -25,63 +25,3 @@ declare module '*.module.scss' {
const classes: { readonly [key: string]: string } const classes: { readonly [key: string]: string }
export default classes export default classes
} }
interface StaticImageData {
src: string
height: number
width: number
placeholder?: string
}
declare module '*.png' {
const content: StaticImageData
export default content
}
declare module '*.svg' {
/**
* Use `any` to avoid conflicts with
* `@svgr/webpack` plugin or
* `babel-plugin-inline-react-svg` plugin.
*/
const content: any
export default content
}
declare module '*.jpg' {
const content: StaticImageData
export default content
}
declare module '*.jpeg' {
const content: StaticImageData
export default content
}
declare module '*.gif' {
const content: StaticImageData
export default content
}
declare module '*.webp' {
const content: StaticImageData
export default content
}
declare module '*.ico' {
const content: StaticImageData
export default content
}
declare module '*.bmp' {
const content: StaticImageData
export default content
}
module.exports = { module.exports = {
images: { images: {
domains: ['via.placeholder.com'], domains: ['via.placeholder.com'],
// disableStaticImages: true,
}, },
} }
/* eslint-env jest */ /* eslint-env jest */
import fs from 'fs-extra'
import { join } from 'path' import { join } from 'path'
import { import {
renderViaHTTP, renderViaHTTP,
...@@ -12,6 +13,7 @@ import { ...@@ -12,6 +13,7 @@ import {
jest.setTimeout(1000 * 60 * 2) jest.setTimeout(1000 * 60 * 2)
const appDir = join(__dirname, '..') const appDir = join(__dirname, '..')
const nextConfig = join(appDir, 'next.config.js')
let appPort let appPort
let app let app
let output let output
...@@ -27,6 +29,23 @@ describe('TypeScript Image Component', () => { ...@@ -27,6 +29,23 @@ describe('TypeScript Image Component', () => {
expect(stderr).toMatch(/Failed to compile/) expect(stderr).toMatch(/Failed to compile/)
expect(stderr).toMatch(/is not assignable to type/) expect(stderr).toMatch(/is not assignable to type/)
expect(code).toBe(1) expect(code).toBe(1)
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8')
expect(envTypes).toContain('image-types/global')
})
it('should remove global image types when disabled', async () => {
const content = await fs.readFile(nextConfig, 'utf8')
await fs.writeFile(
nextConfig,
content.replace('// disableStaticImages', 'disableStaticImages')
)
const { code, stderr } = await nextBuild(appDir, [], { stderr: true })
expect(stderr).toMatch(/Failed to compile/)
expect(stderr).toMatch(/is not assignable to type/)
expect(code).toBe(1)
await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8')
expect(envTypes).not.toContain('image-types/global')
}) })
}) })
...@@ -41,6 +60,11 @@ describe('TypeScript Image Component', () => { ...@@ -41,6 +60,11 @@ describe('TypeScript Image Component', () => {
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
it('should have image types when enabled', async () => {
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8')
expect(envTypes).toContain('image-types/global')
})
it('should render the valid Image usage and not print error', async () => { it('should render the valid Image usage and not print error', async () => {
const html = await renderViaHTTP(appPort, '/valid', {}) const html = await renderViaHTTP(appPort, '/valid', {})
expect(html).toMatch(/This is valid usage of the Image component/) expect(html).toMatch(/This is valid usage of the Image component/)
...@@ -54,4 +78,17 @@ describe('TypeScript Image Component', () => { ...@@ -54,4 +78,17 @@ describe('TypeScript Image Component', () => {
) )
}) })
}) })
it('should remove global image types when disabled (dev)', async () => {
const content = await fs.readFile(nextConfig, 'utf8')
await fs.writeFile(
nextConfig,
content.replace('// disableStaticImages', 'disableStaticImages')
)
const app = await launchApp(appDir, await findPort(), [])
await killApp(app)
await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8')
expect(envTypes).not.toContain('image-types/global')
})
}) })
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