Unverified Commit 570266a4 authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Turbopack: Allow overriding tsconfig path via next-config (#77563)

This:
- Adds a test asserting the user can override the tsconfig path via the
next-config. This is already supported with Next.js and Webpack.
- Implements the necessary code to pass the test and implement support
with Turbopack.

Test Plan: `pnpm test-dev test/e2e/tsconfig-path/index.test.ts && pnpm
test-dev-turbo test/e2e/tsconfig-path/index.test.ts`

Closes PACK-4215
parent 9f76476a
...@@ -2,7 +2,7 @@ use std::iter::once; ...@@ -2,7 +2,7 @@ use std::iter::once;
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{FxIndexMap, ResolvedVc, Value, Vc}; use turbo_tasks::{FxIndexMap, OptionVcExt, ResolvedVc, Value, Vc};
use turbo_tasks_env::EnvMap; use turbo_tasks_env::EnvMap;
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack::{ use turbopack::{
...@@ -169,7 +169,7 @@ pub async fn get_client_resolve_options_context( ...@@ -169,7 +169,7 @@ pub async fn get_client_resolve_options_context(
.to_resolved() .to_resolved()
.await?; .await?;
let custom_conditions = vec![mode.await?.condition().into()]; let custom_conditions = vec![mode.await?.condition().into()];
let module_options_context = ResolveOptionsContext { let resolve_options_context = ResolveOptionsContext {
enable_node_modules: Some(project_path.root().to_resolved().await?), enable_node_modules: Some(project_path.root().to_resolved().await?),
custom_conditions, custom_conditions,
import_map: Some(next_client_import_map), import_map: Some(next_client_import_map),
...@@ -201,16 +201,24 @@ pub async fn get_client_resolve_options_context( ...@@ -201,16 +201,24 @@ pub async fn get_client_resolve_options_context(
)], )],
..Default::default() ..Default::default()
}; };
Ok(ResolveOptionsContext { Ok(ResolveOptionsContext {
enable_typescript: true, enable_typescript: true,
enable_react: true, enable_react: true,
enable_mjs_extension: true, enable_mjs_extension: true,
custom_extensions: next_config.resolve_extension().owned().await?, custom_extensions: next_config.resolve_extension().owned().await?,
tsconfig_path: next_config
.typescript_tsconfig_path()
.await?
.as_ref()
.map(|p| project_path.join(p.to_owned()))
.to_resolved()
.await?,
rules: vec![( rules: vec![(
foreign_code_context_condition(next_config, project_path).await?, foreign_code_context_condition(next_config, project_path).await?,
module_options_context.clone().resolved_cell(), resolve_options_context.clone().resolved_cell(),
)], )],
..module_options_context ..resolve_options_context
} }
.cell()) .cell())
} }
......
...@@ -417,7 +417,7 @@ pub struct Rewrites { ...@@ -417,7 +417,7 @@ pub struct Rewrites {
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct TypeScriptConfig { pub struct TypeScriptConfig {
pub ignore_build_errors: Option<bool>, pub ignore_build_errors: Option<bool>,
pub ts_config_path: Option<String>, pub tsconfig_path: Option<String>,
} }
#[turbo_tasks::value(eq = "manual", operation)] #[turbo_tasks::value(eq = "manual", operation)]
...@@ -1534,6 +1534,16 @@ impl NextConfig { ...@@ -1534,6 +1534,16 @@ impl NextConfig {
Ok(Vc::cell(source_maps.unwrap_or(true))) Ok(Vc::cell(source_maps.unwrap_or(true)))
} }
#[turbo_tasks::function]
pub async fn typescript_tsconfig_path(&self) -> Result<Vc<Option<RcStr>>> {
Ok(Vc::cell(
self.typescript
.tsconfig_path
.as_ref()
.map(|path| path.to_owned().into()),
))
}
} }
/// A subset of ts/jsconfig that next.js implicitly /// A subset of ts/jsconfig that next.js implicitly
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{FxIndexMap, ResolvedVc, Value, Vc}; use turbo_tasks::{FxIndexMap, OptionVcExt, ResolvedVc, Value, Vc};
use turbo_tasks_env::EnvMap; use turbo_tasks_env::EnvMap;
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack::{css::chunk::CssChunkType, resolve_options_context::ResolveOptionsContext}; use turbopack::{css::chunk::CssChunkType, resolve_options_context::ResolveOptionsContext};
...@@ -183,6 +183,7 @@ pub async fn get_edge_resolve_options_context( ...@@ -183,6 +183,7 @@ pub async fn get_edge_resolve_options_context(
browser: true, browser: true,
after_resolve_plugins, after_resolve_plugins,
before_resolve_plugins, before_resolve_plugins,
..Default::default() ..Default::default()
}; };
...@@ -192,6 +193,13 @@ pub async fn get_edge_resolve_options_context( ...@@ -192,6 +193,13 @@ pub async fn get_edge_resolve_options_context(
enable_mjs_extension: true, enable_mjs_extension: true,
enable_edge_node_externals: true, enable_edge_node_externals: true,
custom_extensions: next_config.resolve_extension().owned().await?, custom_extensions: next_config.resolve_extension().owned().await?,
tsconfig_path: next_config
.typescript_tsconfig_path()
.await?
.as_ref()
.map(|p| project_path.join(p.to_owned()))
.to_resolved()
.await?,
rules: vec![( rules: vec![(
foreign_code_context_condition(next_config, project_path).await?, foreign_code_context_condition(next_config, project_path).await?,
resolve_options_context.clone().resolved_cell(), resolve_options_context.clone().resolved_cell(),
......
...@@ -2,7 +2,7 @@ use std::iter::once; ...@@ -2,7 +2,7 @@ use std::iter::once;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{FxIndexMap, ResolvedVc, Value, Vc}; use turbo_tasks::{FxIndexMap, OptionVcExt, ResolvedVc, Value, Vc};
use turbo_tasks_env::{EnvMap, ProcessEnv}; use turbo_tasks_env::{EnvMap, ProcessEnv};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack::{ use turbopack::{
...@@ -324,6 +324,13 @@ pub async fn get_server_resolve_options_context( ...@@ -324,6 +324,13 @@ pub async fn get_server_resolve_options_context(
enable_react: true, enable_react: true,
enable_mjs_extension: true, enable_mjs_extension: true,
custom_extensions: next_config.resolve_extension().owned().await?, custom_extensions: next_config.resolve_extension().owned().await?,
tsconfig_path: next_config
.typescript_tsconfig_path()
.await?
.as_ref()
.map(|p| project_path.join(p.to_owned()))
.to_resolved()
.await?,
rules: vec![( rules: vec![(
foreign_code_context_condition, foreign_code_context_condition,
resolve_options_context.clone().resolved_cell(), resolve_options_context.clone().resolved_cell(),
......
export default async function Layout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export async function generateMetadata() {
return {}
}
import foo from 'foo'
export default function Page() {
return <p>{foo}</p>
}
export default 'bar123'
import { FileRef, nextTestSetup } from 'e2e-utils'
describe('specified tsconfig', () => {
const { next, skipped } = nextTestSetup({
files: new FileRef(__dirname),
dependencies: {
typescript: '5.4.4',
},
})
if (skipped) {
return
}
it('app router: allows a user-specific tsconfig via the next config', async () => {
const html = await next.render('/')
expect(html).toContain('bar123')
})
it('pages router: allows a user-specific tsconfig via the next config', async () => {
const html = await next.render('/page')
expect(html).toContain('bar123')
})
it('middleware: allows a user-specific tsconfig via the next config', async () => {
const html = await next.render('/middleware')
expect(html).toContain('bar123')
})
})
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import foo from 'foo'
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
return NextResponse.json({ foo })
}
// See "Matching Paths" below to learn more
export const config = {
matcher: '/middleware',
}
{
"compilerOptions": {
"paths": {
"foo": ["./bar.ts"]
},
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"noEmit": true,
"incremental": true,
"module": "esnext",
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"plugins": [
{
"name": "next"
}
],
"strictNullChecks": true
},
"include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
typescript: {
tsconfigPath: 'myconfig.json',
},
}
export default nextConfig
import foo from 'foo'
export default function Page() {
return <p>{foo}</p>
}
export default async function Layout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export async function generateMetadata() {
return {}
}
import foo from 'foo'
export default function Page() {
return <p>{foo}</p>
}
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import foo from 'foo'
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
return NextResponse.json({ foo })
}
// See "Matching Paths" below to learn more
export const config = {
matcher: '/middleware',
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
typescript: {
tsconfigPath: 'web.tsconfig.json',
},
}
export default nextConfig
import foo from 'foo'
export default function Page() {
return <p>{foo}</p>
}
/* eslint-env jest */
import { join } from 'path'
import { nextTestSetup, FileRef } from 'e2e-utils'
describe('Custom TypeScript Config', () => {
const { next, skipped } = nextTestSetup({
files: new FileRef(join(__dirname, '..')),
dependencies: {
typescript: '5.4.4',
},
})
if (skipped) {
return
}
it('app router: allows a user-specific tsconfig via the next config', async () => {
const html = await next.render('/')
expect(html).toContain('bar123')
})
it('pages router: allows a user-specific tsconfig via the next config', async () => {
const html = await next.render('/page')
expect(html).toContain('bar123')
})
it('middleware: allows a user-specific tsconfig via the next config', async () => {
const html = await next.render('/middleware')
expect(html).toContain('bar123')
})
})
{
"compilerOptions": {
"paths": {
"foo": ["./bar.ts"]
},
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"noEmit": true,
"incremental": true,
"module": "esnext",
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"plugins": [
{
"name": "next"
}
],
"strictNullChecks": true
},
"include": ["**/*.ts", "**/*.tsx", "next-env.d.ts", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
...@@ -293,12 +293,35 @@ pub async fn resolve_options( ...@@ -293,12 +293,35 @@ pub async fn resolve_options(
let resolve_options = base_resolve_options(resolve_path, options_context); let resolve_options = base_resolve_options(resolve_path, options_context);
let resolve_options = if options_context_value.enable_typescript { let resolve_options = if options_context_value.enable_typescript {
let tsconfig = find_context_file(resolve_path, tsconfig()).await?; let find_tsconfig = async || {
match *tsconfig { // Otherwise, attempt to find a tsconfig up the file tree
FindContextFileResult::Found(path, _) => { let tsconfig = find_context_file(resolve_path, tsconfig()).await?;
apply_tsconfig_resolve_options(resolve_options, tsconfig_resolve_options(*path)) anyhow::Ok::<Vc<ResolveOptions>>(match *tsconfig {
FindContextFileResult::Found(path, _) => {
apply_tsconfig_resolve_options(resolve_options, tsconfig_resolve_options(*path))
}
FindContextFileResult::NotFound(_) => resolve_options,
})
};
// Use a specified tsconfig path if provided. In Next.js, this is always provided by the
// default config, at the very least.
if let Some(tsconfig_path) = options_context_value.tsconfig_path {
let meta = tsconfig_path.metadata().await;
if meta.is_ok() {
// If the file exists, use it.
apply_tsconfig_resolve_options(
resolve_options,
tsconfig_resolve_options(*tsconfig_path),
)
} else {
// Otherwise, try and find one.
// TODO: If the user provides a tsconfig.json explicitly, this should fail
// explicitly. Currently implemented this way for parity with webpack.
find_tsconfig().await?
} }
FindContextFileResult::NotFound(_) => resolve_options, } else {
find_tsconfig().await?
} }
} else { } else {
resolve_options resolve_options
......
...@@ -32,6 +32,10 @@ pub struct ResolveOptionsContext { ...@@ -32,6 +32,10 @@ pub struct ResolveOptionsContext {
/// directory /// directory
pub enable_node_modules: Option<ResolvedVc<FileSystemPath>>, pub enable_node_modules: Option<ResolvedVc<FileSystemPath>>,
#[serde(default)] #[serde(default)]
/// A specific path to a tsconfig.json file to use for resolving modules. If `None`, one will
/// be looked up through the filesystem
pub tsconfig_path: Option<ResolvedVc<FileSystemPath>>,
#[serde(default)]
/// Mark well-known Node.js modules as external imports and load them using /// Mark well-known Node.js modules as external imports and load them using
/// native `require`. e.g. url, querystring, os /// native `require`. e.g. url, querystring, os
pub enable_node_externals: bool, pub enable_node_externals: bool,
......
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