Skip to content

Commit

Permalink
fix: fallback to load types from builtin twind
Browse files Browse the repository at this point in the history
  • Loading branch information
sastan committed Mar 22, 2021
1 parent 2901cc3 commit 96064f1
Showing 1 changed file with 43 additions and 3 deletions.
46 changes: 43 additions & 3 deletions src/twind.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import * as path from 'path'
import Module from 'module'
import { fileURLToPath, pathToFileURL } from 'url'

import type { Logger } from 'typescript-template-language-service-decorator'
import type * as TS from 'typescript/lib/tsserverlibrary'
Expand Down Expand Up @@ -235,7 +237,7 @@ export class Twind {
return this._state
}

const program = this.info.languageService.getProgram()
let program = this.info.languageService.getProgram()

if (!program) {
return undefined
Expand Down Expand Up @@ -263,17 +265,55 @@ export class Twind {
})

// Prefer project twind and fallback to bundled twind
const twindDTSFile = this.info.project
let twindDTSFile = this.info.project
.resolveModuleNames(['twind'], program.getRootFileNames()[0])
.map((moduleName) => moduleName?.resolvedFileName)[0]

const twindDTSSourceFile =
this.logger.log('local twind dts: ' + twindDTSFile)

let twindDTSSourceFile =
(twindDTSFile &&
program.getSourceFiles().find((sourceFile) => sourceFile.fileName == twindDTSFile)) ||
program
.getSourceFiles()
.find((sourceFile) => sourceFile.fileName.endsWith('twind/twind.d.ts'))

// No local twind but a twind.config -> use our twind
if (
!twindDTSFile &&
!twindDTSSourceFile &&
configFile &&
/twind\.config\.\w+$/.test(configFile)
) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const from: string | URL = import.meta.url || pathToFileURL(__filename)

const { resolve } =
Module.createRequire?.(from) || Module.createRequireFromPath(fileURLToPath(from))

try {
twindDTSFile = resolve('twind').replace(/\.\w+$/, '.d.ts')
this.logger.log('builtin twind dts: ' + twindDTSFile)
} catch {
// ignore
}
}

if (twindDTSFile) {
program = this.typescript.createProgram({
rootNames: [...program.getRootFileNames(), twindDTSFile],
options: program.getCompilerOptions(),
// projectReferences?: readonly ProjectReference[];
// host?: program.getCom
oldProgram: program,
})

twindDTSSourceFile = program
.getSourceFiles()
.find((sourceFile) => sourceFile.fileName.endsWith('twind/twind.d.ts'))
}

this.logger.log('twindDTSSourceFile: ' + twindDTSSourceFile?.fileName)

if (twindDTSSourceFile) {
Expand Down

0 comments on commit 96064f1

Please sign in to comment.