Skip to content

Instantly share code, notes, and snippets.

@odiak
Created December 25, 2024 17:30
Show Gist options
  • Save odiak/7b12390f17e4d1440f2174b4fc418fae to your computer and use it in GitHub Desktop.
Save odiak/7b12390f17e4d1440f2174b4fc418fae to your computer and use it in GitHub Desktop.
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