Skip to content

Commit

Permalink
fix(shadcn): handling of tsconfig aliases (#5813)
Browse files Browse the repository at this point in the history
* fix(shadcn): handling of tsconfig aliases

* chore: add changeset
  • Loading branch information
shadcn authored Nov 13, 2024
1 parent fb36ca4 commit d5bf001
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 11 deletions.
5 changes: 5 additions & 0 deletions .changeset/fresh-turtles-cheat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"shadcn": patch
---

fix handling of aliases
44 changes: 33 additions & 11 deletions packages/shadcn/src/utils/get-project-info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { getPackageInfo } from "@/src/utils/get-package-info"
import fg from "fast-glob"
import fs from "fs-extra"
import { loadConfig } from "tsconfig-paths"
import { z } from "zod"

type ProjectInfo = {
framework: Framework
Expand All @@ -29,6 +30,12 @@ const PROJECT_SHARED_IGNORE = [
"build",
]

const TS_CONFIG_SCHEMA = z.object({
compilerOptions: z.object({
paths: z.record(z.string().or(z.array(z.string()))),
}),
})

export async function getProjectInfo(cwd: string): Promise<ProjectInfo | null> {
const [
configFiles,
Expand Down Expand Up @@ -153,7 +160,10 @@ export async function getTailwindConfigFile(cwd: string) {
export async function getTsConfigAliasPrefix(cwd: string) {
const tsConfig = await loadConfig(cwd)

if (tsConfig?.resultType === "failed" || !tsConfig?.paths) {
if (
tsConfig?.resultType === "failed" ||
!Object.entries(tsConfig?.paths).length
) {
return null
}

Expand All @@ -169,7 +179,8 @@ export async function getTsConfigAliasPrefix(cwd: string) {
}
}

return null
// Use the first alias as the prefix.
return Object.keys(tsConfig?.paths)?.[0].replace(/\/\*$/, "") ?? null
}

export async function isTypeScriptProject(cwd: string) {
Expand All @@ -182,19 +193,30 @@ export async function isTypeScriptProject(cwd: string) {
return files.length > 0
}

export async function getTsConfig() {
try {
const tsconfigPath = path.join("tsconfig.json")
const tsconfig = await fs.readJSON(tsconfigPath)
export async function getTsConfig(cwd: string) {
for (const fallback of [
"tsconfig.json",
"tsconfig.web.json",
"tsconfig.app.json",
]) {
const filePath = path.resolve(cwd, fallback)
if (!(await fs.pathExists(filePath))) {
continue
}

if (!tsconfig) {
throw new Error("tsconfig.json is missing")
// We can't use fs.readJSON because it doesn't support comments.
const contents = await fs.readFile(filePath, "utf8")
const cleanedContents = contents.replace(/\/\*\s*\*\//g, "")
const result = TS_CONFIG_SCHEMA.safeParse(JSON.parse(cleanedContents))

if (result.error) {
continue
}

return tsconfig
} catch (error) {
return null
return result.data
}

return null
}

export async function getProjectConfig(
Expand Down

0 comments on commit d5bf001

Please sign in to comment.