Created
December 25, 2024 17:30
-
-
Save odiak/7b12390f17e4d1440f2174b4fc418fae to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ts from 'typescript'; | |
import vue from '@vue/language-core'; | |
import fs from 'fs'; | |
import path from 'path'; | |
import { proxyCreateProgram } from '@volar/typescript'; | |
function main() { | |
const workspace = '.'; | |
const compilerOptions: ts.CompilerOptions = { | |
rootDir: workspace, | |
declaration: true, | |
emitDeclarationOnly: true, | |
allowNonTsExtensions: true, | |
}; | |
const host = ts.createCompilerHost(compilerOptions); | |
const options: ts.CreateProgramOptions = { | |
host, | |
rootNames: readFilesRecursive(path.join(workspace, 'src')), | |
options: compilerOptions, | |
}; | |
let vueOptions: vue.VueCompilerOptions; | |
const createProgram = proxyCreateProgram( | |
ts, | |
ts.createProgram, | |
(ts, options) => { | |
const { configFilePath } = options.options; | |
if (typeof configFilePath === 'string') { | |
vueOptions = vue.createParsedCommandLine( | |
ts, | |
ts.sys, | |
configFilePath | |
).vueOptions; | |
} else { | |
vueOptions = vue.resolveVueCompilerOptions({ | |
extensions: ['.vue'], | |
}); | |
vueOptions.__setupedGlobalTypes = vue.setupGlobalTypes( | |
workspace, | |
vueOptions, | |
ts.sys | |
); | |
} | |
const vueLanguagePlugin = vue.createVueLanguagePlugin<string>( | |
ts, | |
options.options, | |
vueOptions, | |
(id) => id | |
); | |
return [vueLanguagePlugin]; | |
} | |
); | |
const program = createProgram(options); | |
const sourceFile = program.getSourceFile('./src/components/Test2.vue'); | |
console.log(sourceFile?.getFullText()); | |
} | |
function readFilesRecursive(dir: string) { | |
const result: string[] = []; | |
for (const file of fs.readdirSync(dir)) { | |
const filepath = path.join(dir, file); | |
const stat = fs.statSync(filepath); | |
if (stat.isDirectory()) { | |
result.push(...readFilesRecursive(filepath)); | |
} else if (path.extname(file) === '.vue') { | |
result.push(filepath); | |
} | |
} | |
return result; | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment