TypeScript
Plugin design
Write a language service plugin skeleton.
What is a language service plugin?
A language service plugin is a function that decorates the TypeScript language service. It takes a ts.server.PluginCreateInfo and returns a ts.LanguageService. The plugin is enabled by adding it to the plugins array in tsconfig.json.
import ts from "typescript";
function createPlugin(
info: ts.server.PluginCreateInfo
): ts.LanguageService {
const ls = info.languageService;
return { ...ls };
}
export = createPlugin;
Plugin skeleton
The skeleton takes the existing language service and wraps its methods. You override methods like getSemanticDiagnostics: first take ls's result, add extras, and return.
return {
...ls,
getSemanticDiagnostics: function(fileName) {
const prior = ls.getSemanticDiagnostics(fileName);
return prior;
},
};
Exercise Plugin skeleton
Write a plugin function that takes ts.server.PluginCreateInfo and returns ts.LanguageService. Get ls from info.languageService, wrap getSemanticDiagnostics and return ls's diagnostics as-is. Write a test: a mock language service returns 1 diagnostic; call the plugin and print the diagnostic count.
Show example solution
import ts from "typescript";
function createPlugin(info: ts.server.PluginCreateInfo): ts.LanguageService {
const ls = info.languageService;
return {
...ls,
getSemanticDiagnostics: function(fileName: string) {
return ls.getSemanticDiagnostics(fileName);
},
};
}
const fakeLs = {
getSemanticDiagnostics: function(_fileName: string): ts.Diagnostic[] {
return [{ category: ts.DiagnosticCategory.Error, code: 1, messageText: "test", file: undefined, start: 0, length: 1 } as ts.Diagnostic];
},
} as unknown as ts.LanguageService;
const info = { languageService: fakeLs, config: {} } as unknown as ts.server.PluginCreateInfo;
const plugin = createPlugin(info);
const diags = plugin.getSemanticDiagnostics("app.ts");
console.log(diags.length);
Test yourself
-
What does a language service plugin return?
- ts.Diagnostic[]
- ts.SourceFile
- ts.LanguageService
- ts.Program
Show answer
ts.LanguageService — A plugin takes PluginCreateInfo and returns a decorated LanguageService. It does not return a Program, Diagnostic[] or SourceFile.
-
Get the language service
function createPlugin(info: ts.server.PluginCreateInfo): ts.LanguageService {
const ls = info.____;
return { ...ls };
}
Show answer
function createPlugin(info: ts.server.PluginCreateInfo): ts.LanguageService {
const ls = info.languageService;
return { ...ls };
}
-
Plugin skeleton parts
- PluginCreateInfo
- Plugin input
- info.languageService
- Existing language service
- ts.LanguageService
- Plugin output
- getSemanticDiagnostics
- Decorated method
Next lesson: Diagnostic production