Unverified Commit 9343b67c authored by Casper's avatar Casper Committed by GitHub

feat: allow setting custom tsconfig file (#28104)



Ability to provide a custom tsconfig file. 

**Example Usage:**

```js
// next.config.js
module.exports = {
	typescript: {
		tsconfigPath: "myconfig.json"
	}
}
```


## Bug

- [ ] 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.
- [x] Related issues linked using [`fixes #23972 (discussion)`](https://github.com/vercel/next.js/discussions/23972)
- [x] Integration tests added
- [x] 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

- [x] Make sure the linting passes
parent c3a395ab
......@@ -35,6 +35,8 @@ touch tsconfig.json
Next.js will automatically configure this file with default values. Providing your own `tsconfig.json` with custom [compiler options](https://www.typescriptlang.org/docs/handbook/compiler-options.html) is also supported.
You can also provide a relative path to a tsconfig.json file by setting `typescript.tsconfigPath` prop inside your `next.config.js` file.
> Next.js uses Babel to handle TypeScript, which has some [caveats](https://babeljs.io/docs/en/babel-plugin-transform-typescript#caveats), and some [compiler options are handled differently](https://babeljs.io/docs/en/babel-plugin-transform-typescript#typescript-compiler-options).
Then, run `next` (normally `npm run dev` or `yarn dev`) and Next.js will guide you through the installation of the required packages to finish the setup:
......
......@@ -196,7 +196,7 @@ export default async function build(
dir,
pagesDir,
!ignoreTypeScriptErrors,
!config.images.disableStaticImages,
config,
cacheDir
)
)
......
......@@ -203,6 +203,8 @@ const NODE_ESM_RESOLVE_OPTIONS = {
fullySpecified: true,
}
let TSCONFIG_WARNED = false
export default async function getBaseWebpackConfig(
dir: string,
{
......@@ -378,7 +380,7 @@ export default async function getBaseWebpackConfig(
try {
typeScriptPath = require.resolve('typescript', { paths: [dir] })
} catch (_) {}
const tsConfigPath = path.join(dir, 'tsconfig.json')
const tsConfigPath = path.join(dir, config.typescript.tsconfigPath)
const useTypeScript = Boolean(
typeScriptPath && (await fileExists(tsConfigPath))
)
......@@ -386,6 +388,14 @@ export default async function getBaseWebpackConfig(
let jsConfig
// jsconfig is a subset of tsconfig
if (useTypeScript) {
if (
config.typescript.tsconfigPath !== 'tsconfig.json' &&
TSCONFIG_WARNED === false
) {
TSCONFIG_WARNED = true
Log.info(`Using tsconfig file: ${config.typescript.tsconfigPath}`)
}
const ts = (await import(typeScriptPath!)) as typeof import('typescript')
const tsConfig = await getTypeScriptConfiguration(ts, tsConfigPath, true)
jsConfig = { compilerOptions: tsConfig.options }
......
import { promises as fs } from 'fs'
import path from 'path'
import { NextConfigComplete } from '../../server/config-shared'
import { fileExists } from '../file-exists'
import { recursiveReadDir } from '../recursive-readdir'
......@@ -7,9 +8,10 @@ export type TypeScriptIntent = { firstTimeSetup: boolean }
export async function getTypeScriptIntent(
baseDir: string,
pagesDir: string
pagesDir: string,
config: NextConfigComplete
): Promise<TypeScriptIntent | false> {
const tsConfigPath = path.join(baseDir, 'tsconfig.json')
const tsConfigPath = path.join(baseDir, config.typescript.tsconfigPath)
// The integration turns on if we find a `tsconfig.json` in the user's
// project.
......
......@@ -14,6 +14,7 @@ import { TypeCheckResult } from './typescript/runTypeCheck'
import { writeAppTypeDeclarations } from './typescript/writeAppTypeDeclarations'
import { writeConfigurationDefaults } from './typescript/writeConfigurationDefaults'
import { missingDepsError } from './typescript/missingDependencyError'
import { NextConfigComplete } from '../server/config-shared'
const requiredPackages = [
{ file: 'typescript', pkg: 'typescript' },
......@@ -25,14 +26,14 @@ export async function verifyTypeScriptSetup(
dir: string,
pagesDir: string,
typeCheckPreflight: boolean,
imageImportsEnabled: boolean,
config: NextConfigComplete,
cacheDir?: string
): Promise<{ result?: TypeCheckResult; version: string | null }> {
const tsConfigPath = path.join(dir, 'tsconfig.json')
const tsConfigPath = path.join(dir, config.typescript.tsconfigPath)
try {
// Check if the project uses TypeScript:
const intent = await getTypeScriptIntent(dir, pagesDir)
const intent = await getTypeScriptIntent(dir, pagesDir, config)
if (!intent) {
return { version: null }
}
......@@ -62,7 +63,7 @@ export async function verifyTypeScriptSetup(
await writeConfigurationDefaults(ts, tsConfigPath, intent.firstTimeSetup)
// Write out the necessary `next-env.d.ts` file to correctly register
// Next.js' types:
await writeAppTypeDeclarations(dir, imageImportsEnabled)
await writeAppTypeDeclarations(dir, !config.images.disableStaticImages)
let result
if (typeCheckPreflight) {
......
......@@ -8,6 +8,7 @@ import {
export type NextConfigComplete = Required<NextConfig> & {
images: ImageConfigComplete
typescript: Required<TypeScriptConfig>
}
export interface I18NConfig {
......@@ -34,6 +35,8 @@ export interface ESLintConfig {
export interface TypeScriptConfig {
/** Do not run TypeScript during production builds (`next build`). */
ignoreBuildErrors?: boolean
/** Relative path to a custom tsconfig file */
tsconfigPath?: string
}
export type NextConfig = { [key: string]: any } & {
......@@ -153,6 +156,7 @@ export const defaultConfig: NextConfig = {
},
typescript: {
ignoreBuildErrors: false,
tsconfigPath: 'tsconfig.json',
},
distDir: '.next',
cleanDistDir: true,
......
......@@ -290,7 +290,7 @@ export default class DevServer extends Server {
this.dir,
this.pagesDir!,
false,
!this.nextConfig.images.disableStaticImages
this.nextConfig
)
this.customRoutes = await loadCustomRoutes(this.nextConfig)
......
module.exports = {
typescript: {
tsconfigPath: 'web.tsconfig.json',
},
}
export default function Index() {
return <p>Hello world</p>
}
/* eslint-env jest */
import { join } from 'path'
import { nextBuild } from 'next-test-utils'
const appDir = join(__dirname, '..')
const warnMessage = /Using tsconfig file:/
describe('Custom TypeScript Config', () => {
it('should warn when using custom typescript path', async () => {
const { stdout } = await nextBuild(appDir, [], {
stdout: true,
})
expect(stdout).toMatch(warnMessage)
})
})
{
"compilerOptions": {
"target": "es5",
"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"]
}
......@@ -98,6 +98,11 @@ export default function EvilPage(): JSX.Element {
expect(output.code).toBe(0)
})
it('should not inform when using default tsconfig path', async () => {
const output = await nextBuild(appDir, [], { stdout: true })
expect(output.stdout).not.toMatch(/Using tsconfig file:/)
})
describe('should compile with different types', () => {
it('should compile async getInitialProps for _error', async () => {
const errorPage = new File(join(appDir, 'pages/_error.tsx'))
......
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