Unverified Commit ba33b4e3 authored by Hamidreza Hanafi's avatar Hamidreza Hanafi Committed by GitHub

Resolve `compilerOptions.paths` in tsconfigs without `compilerOptions.baseUrl` (#92277)

Co-authored-by: 's avatarSebastian Sebbie Silbermann <sebastian.silbermann@vercel.com>
parent a9a8e272
...@@ -102,9 +102,18 @@ export default async function loadJsConfig( ...@@ -102,9 +102,18 @@ export default async function loadJsConfig(
isImplicit: false, isImplicit: false,
} }
} else { } else {
if (implicitBaseurl) { // TypeScript 5.0+: `pathsBasePath` is the directory of the tsconfig that
// defines `paths`. For paths inherited from an extended base tsconfig (e.g.
// a workspace-root tsconfig.base.json for nx monorepo), this is the base
// config's directory — not the app tsconfig dir. Using it ensures JsConfigPathsPlugin
// joins path-mapping values against the correct base so `baseUrl` is not required
// for path aliases to work in webpack.
const pathsBasePath: string | undefined =
jsConfig?.compilerOptions?.pathsBasePath
const effectiveBaseUrl = pathsBasePath ?? implicitBaseurl
if (effectiveBaseUrl) {
resolvedBaseUrl = { resolvedBaseUrl = {
baseUrl: implicitBaseurl, baseUrl: effectiveBaseUrl,
isImplicit: true, isImplicit: true,
} }
} }
......
...@@ -17,13 +17,21 @@ describe('tsconfig-path-reloading', () => { ...@@ -17,13 +17,21 @@ describe('tsconfig-path-reloading', () => {
const tsConfigFile = 'tsconfig.json' const tsConfigFile = 'tsconfig.json'
const indexPage = 'pages/index.tsx' const indexPage = 'pages/index.tsx'
function runTests({ addAfterStart }: { addAfterStart?: boolean }) { function runTests({
addAfterStart,
testBaseUrl,
}: {
addAfterStart?: boolean
testBaseUrl: boolean
}) {
beforeAll(async () => { beforeAll(async () => {
let tsConfigContent = await fs.readFile( let tsConfigContent = await fs.readFile(
join(__dirname, 'app/tsconfig.json'), join(__dirname, 'app/tsconfig.json'),
'utf8' 'utf8'
) )
const typescriptVersion = testBaseUrl ? '5.9.3' : 'latest'
next = await createNext({ next = await createNext({
files: { files: {
components: new FileRef(join(__dirname, 'app/components')), components: new FileRef(join(__dirname, 'app/components')),
...@@ -36,7 +44,7 @@ describe('tsconfig-path-reloading', () => { ...@@ -36,7 +44,7 @@ describe('tsconfig-path-reloading', () => {
}), }),
}, },
dependencies: { dependencies: {
typescript: 'latest', typescript: typescriptVersion,
'@types/react': 'latest', '@types/react': 'latest',
'@types/node': 'latest', '@types/node': 'latest',
}, },
...@@ -183,10 +191,18 @@ describe('tsconfig-path-reloading', () => { ...@@ -183,10 +191,18 @@ describe('tsconfig-path-reloading', () => {
} }
describe('tsconfig', () => { describe('tsconfig', () => {
runTests({}) runTests({ testBaseUrl: true })
})
describe('tsconfig without baseUrl', () => {
runTests({ testBaseUrl: false })
}) })
describe('tsconfig added after starting dev', () => { describe('tsconfig added after starting dev', () => {
runTests({ addAfterStart: true }) runTests({ testBaseUrl: true, addAfterStart: true })
})
describe('tsconfig without baseUrl added after starting dev', () => {
runTests({ testBaseUrl: false, addAfterStart: true })
}) })
}) })
import { nextTestSetup } from 'e2e-utils'
describe('app-dir alias', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should handle typescript paths alias correctly', async () => {
const html = await next.render('/button')
expect(html).toContain('click</button>')
})
it('should resolve css imports from outside with src folder presented', async () => {
const browser = await next.browser('/button')
const fontSize = await browser
.elementByCss('button')
.getComputedCss('font-size')
expect(fontSize).toBe('50px')
})
})
...@@ -3,6 +3,9 @@ import { nextTestSetup } from 'e2e-utils' ...@@ -3,6 +3,9 @@ import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-import-alias-paths-with-baseurl-cjs', () => { describe('next-config-ts-import-alias-paths-with-baseurl-cjs', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
dependencies: {
typescript: '5.9.3',
},
}) })
it('should support import alias paths with baseUrl (CJS)', async () => { it('should support import alias paths with baseUrl (CJS)', async () => {
......
...@@ -4,6 +4,9 @@ describe('next-config-ts-import-alias-paths-with-baseurl-esm', () => { ...@@ -4,6 +4,9 @@ describe('next-config-ts-import-alias-paths-with-baseurl-esm', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
packageJson: { packageJson: {
dependencies: {
typescript: '5.9.3',
},
type: 'module', type: 'module',
}, },
}) })
......
import type { NextConfig } from 'next' import type { NextConfig } from 'next'
import { foo } from '@/foo' import { foo } from '@/foo'
import { bar } from 'bar' import { bar } from '#/bar'
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
env: { env: {
......
{ {
"compilerOptions": { "compilerOptions": {
"baseUrl": ".",
"paths": { "paths": {
"@/*": ["./src/*"] "@/*": ["./src/*"],
"#/*": ["./*"]
} }
} }
} }
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES6", "target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"], "lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
"strict": true, "strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true, "noEmit": true,
"esModuleInterop": true, "incremental": true,
"module": "esnext", "module": "esnext",
"esModuleInterop": true,
"moduleResolution": "bundler", "moduleResolution": "bundler",
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "react-jsx", "jsx": "react-jsx",
"incremental": true,
"baseUrl": ".",
"paths": {
"@/ui/*": ["ui/*"]
},
"plugins": [ "plugins": [
{ {
"name": "next" "name": "next"
} }
] ]
}, },
"include": [ "include": ["next-env.d.ts", "**/*.mts", "**/*.ts", "**/*.tsx"],
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"] "exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
} }
import { execSync } from 'child_process'
import { nextTestSetup } from 'e2e-utils'
describe('app-dir types', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
skipStart: true,
})
if (skipped) {
return
}
it('should check types', async () => {
execSync('pnpm next typegen', { cwd: next.testDir, stdio: 'inherit' })
execSync('pnpm tsc', { cwd: next.testDir, stdio: 'inherit' })
})
})
import Button from '@/ui/button' import { Hello } from '@mycomponent'
import React from 'react' import React from 'react'
export default function page() { export default function page() {
...@@ -6,5 +6,5 @@ export default function page() { ...@@ -6,5 +6,5 @@ export default function page() {
throw new Error('React is not resolved correctly.') throw new Error('React is not resolved correctly.')
} }
return <Button>click</Button> return <Hello />
} }
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
/* eslint-env jest */ /* eslint-env jest */
import { join } from 'path' import { join } from 'path'
import cheerio from 'cheerio'
import * as path from 'path' import * as path from 'path'
import { import { nextTestSetup, type NextInstance } from 'e2e-utils'
renderViaHTTP, import { File } from 'next-test-utils'
findPort,
launchApp,
killApp,
File,
} from 'next-test-utils'
import * as JSON5 from 'json5' import * as JSON5 from 'json5'
const appDir = join(__dirname, '..') function runTests(next: NextInstance) {
let appPort
let app
async function get$(path, query?: any) {
const html = await renderViaHTTP(appPort, path, query)
return cheerio.load(html)
}
function runTests() {
describe('default behavior', () => { describe('default behavior', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort, {})
})
afterAll(() => killApp(app))
it('should alias components', async () => { it('should alias components', async () => {
const $ = await get$('/basic-alias') const $ = await next.render$('/basic-alias')
expect($('body').text()).toMatch(/World/) expect($('body').text()).toMatch(/World/)
}) })
it('should resolve the first item in the array first', async () => { it('should resolve the first item in the array first', async () => {
const $ = await get$('/resolve-order') const $ = await next.render$('/resolve-order')
expect($('body').text()).toMatch(/Hello from a/) expect($('body').text()).toMatch(/Hello from a/)
}) })
it('should resolve the second item in as a fallback', async () => { it('should resolve the second item in as a fallback', async () => {
const $ = await get$('/resolve-fallback') const $ = await next.render$('/resolve-fallback')
expect($('body').text()).toMatch(/Hello from only b/) expect($('body').text()).toMatch(/Hello from only b/)
}) })
it('should resolve a single matching alias', async () => { it('should resolve a single matching alias', async () => {
const $ = await get$('/single-alias') const $ = await next.render$('/single-alias')
expect($('body').text()).toMatch(/Hello/) expect($('body').text()).toMatch(/Hello/)
}) })
it('should not resolve to .d.ts files', async () => { it('should not resolve to .d.ts files', async () => {
const $ = await get$('/alias-to-d-ts') const $ = await next.render$('/alias-to-d-ts')
expect($('body').text()).toMatch(/Not aliased to d\.ts file/) expect($('body').text()).toMatch(/Not aliased to d\.ts file/)
}) })
it('should handle typescript paths alias correctly', async () => {
const html = await next.render('/button')
expect(html).toContain('Hello')
})
}) })
} }
describe('typescript paths', () => { describe('typescript paths', () => {
runTests() const { next } = nextTestSetup({
files: join(__dirname, '..'),
dependencies: {
// `baseUrl` is deprecated in TypeScript 6.
typescript: '5.9.3',
},
})
runTests(next)
}) })
const tsconfig = new File(path.resolve(__dirname, '../tsconfig.json')) const tsconfig = new File(path.resolve(__dirname, '../tsconfig.json'))
...@@ -83,5 +74,7 @@ describe('typescript paths without baseurl', () => { ...@@ -83,5 +74,7 @@ describe('typescript paths without baseurl', () => {
tsconfig.restore() tsconfig.restore()
}) })
runTests() const { next } = nextTestSetup({ files: join(__dirname, '..') })
runTests(next)
}) })
/* eslint-env jest */
import { join } from 'path'
import { nextTestSetup, isNextDev } from 'e2e-utils'
import { readFileSync, writeFileSync } from 'fs'
describe('TypeScript Features', () => {
describe.each([
{ label: '', testBaseUrl: true },
{ label: ' without baseUrl', testBaseUrl: false },
])('default behavior$label', ({ testBaseUrl }) => {
const tsConfigPath = join(__dirname, '../../../tsconfig.json')
let previousTsConfigJsonc: string | null = null
beforeAll(async () => {
if (testBaseUrl) {
previousTsConfigJsonc = readFileSync(tsConfigPath, 'utf-8')
const nextTsConfigJsonc = previousTsConfigJsonc
.replace('// baseUrl will go here', '"baseUrl": ".",')
.replace(
'./packages/www/types/unfetch.d.ts',
'packages/www/types/unfetch.d.ts'
)
.replace('./packages/www/components/*', 'packages/www/components/*')
.replace('./packages/lib/a/*', 'packages/lib/a/*')
.replace('./packages/lib/b/*', 'packages/lib/b/*')
.replace(
'./packages/www/components/hello.tsx',
'packages/www/components/hello.tsx'
)
.replace(
'./packages/www/components/alias-to-d-ts.d.ts',
'packages/www/components/alias-to-d-ts.d.ts'
)
.replace(
'./packages/www/components/alias-to-d-ts.tsx',
'packages/www/components/alias-to-d-ts.tsx'
)
writeFileSync(tsConfigPath, nextTsConfigJsonc)
}
})
afterAll(() => {
if (previousTsConfigJsonc !== null) {
writeFileSync(tsConfigPath, previousTsConfigJsonc)
}
})
const { next } = nextTestSetup({
skipDeployment: true,
dependencies: testBaseUrl
? {
typescript: '5.9.3',
}
: undefined,
files: join(__dirname, '../../../'),
buildCommand: 'pnpm next build packages/www',
startCommand:
'pnpm next ' + (isNextDev ? 'dev' : 'start') + ' packages/www',
})
it('should alias components', async () => {
const $ = await next.render$('/basic-alias')
expect($('body').text()).toMatch(/World/)
})
it('should resolve the first item in the array first', async () => {
const $ = await next.render$('/resolve-order')
expect($('body').text()).toMatch(/Hello from a/)
})
it('should resolve the second item in as a fallback', async () => {
const $ = await next.render$('/resolve-fallback')
expect($('body').text()).toMatch(/Hello from only b/)
})
it('should resolve a single matching alias', async () => {
const $ = await next.render$('/single-alias')
expect($('body').text()).toMatch(/Hello/)
})
it('should not resolve to .d.ts files', async () => {
const $ = await next.render$('/alias-to-d-ts')
expect($('body').text()).toMatch(/Not aliased to d\.ts file/)
})
})
})
/* This is a single line comment to check if that works */ /* This is a single line comment to check if that works */
{ {
"extends": "../../tsconfig.json", "extends": "../../tsconfig.json",
"exclude": ["node_modules"],
"include": ["next-env.d.ts", "components", "pages"] "include": ["next-env.d.ts", "components", "pages"]
} }
/* This is a single line comment to check if that works */ /* This is a single line comment to check if that works */
{ {
"compilerOptions": { "compilerOptions": {
"baseUrl": ".", // baseUrl will go here
"paths": { "paths": {
"isomorphic-unfetch": ["packages/www/types/unfetch.d.ts"], "isomorphic-unfetch": ["./packages/www/types/unfetch.d.ts"],
"@c/*": ["packages/www/components/*"], "@c/*": ["./packages/www/components/*"],
"@lib/*": ["packages/lib/a/*", "packages/lib/b/*"], "@lib/*": ["./packages/lib/a/*", "./packages/lib/b/*"],
"@mycomponent": ["packages/www/components/hello.tsx"], "@mycomponent": ["./packages/www/components/hello.tsx"],
"d-ts-alias": [ "d-ts-alias": [
"packages/www/components/alias-to-d-ts.d.ts", "./packages/www/components/alias-to-d-ts.d.ts",
"packages/www/components/alias-to-d-ts.tsx" "./packages/www/components/alias-to-d-ts.tsx"
] ]
// This is a single line comment to check if that works // This is a single line comment to check if that works
}, },
......
import React, { type JSX } from 'react'
export function Hi(): JSX.Element {
return <>Hi</>
}
import React, { type JSX } from 'react'
import { World } from 'components/world'
export default function HelloPage(): JSX.Element {
return (
<div>
<World />
</div>
)
}
/* eslint-env jest */
import { join } from 'path'
import cheerio from 'cheerio'
import { renderViaHTTP, findPort, launchApp, killApp } from 'next-test-utils'
const appDir = join(__dirname, '..')
let appPort
let app
async function get$(path, query?: any) {
const html = await renderViaHTTP(appPort, path, query)
return cheerio.load(html)
}
describe('TypeScript Features', () => {
describe('default behavior', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort, {})
})
afterAll(() => killApp(app))
it('should render the page', async () => {
const $ = await get$('/hello')
expect($('body').text()).toMatch(/World/)
})
})
})
{
"compilerOptions": {
"baseUrl": ".",
"esModuleInterop": true,
"module": "esnext",
"jsx": "react-jsx",
"target": "es2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true
},
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"],
"include": ["next-env.d.ts", "components", "pages"]
}
module.exports = {
onDemandEntries: {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60,
},
}
import React, { type JSX } from 'react'
export function World(): JSX.Element {
return <>World</>
}
/* eslint-env jest */
import { join } from 'path'
import cheerio from 'cheerio'
import { renderViaHTTP, findPort, launchApp, killApp } from 'next-test-utils'
const appDir = join(__dirname, '..')
let appPort
let app
async function get$(path, query?: any) {
const html = await renderViaHTTP(appPort, path, query)
return cheerio.load(html)
}
describe('TypeScript Features', () => {
describe('default behavior', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort, {})
})
afterAll(() => killApp(app))
it('should alias components', async () => {
const $ = await get$('/basic-alias')
expect($('body').text()).toMatch(/World/)
})
it('should resolve the first item in the array first', async () => {
const $ = await get$('/resolve-order')
expect($('body').text()).toMatch(/Hello from a/)
})
it('should resolve the second item in as a fallback', async () => {
const $ = await get$('/resolve-fallback')
expect($('body').text()).toMatch(/Hello from only b/)
})
it('should resolve a single matching alias', async () => {
const $ = await get$('/single-alias')
expect($('body').text()).toMatch(/Hello/)
})
it('should not resolve to .d.ts files', async () => {
const $ = await get$('/alias-to-d-ts')
expect($('body').text()).toMatch(/Not aliased to d\.ts file/)
})
})
})
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