Svelte Language Server
The Svelte Language Server (package `svelte-language-server`, currently at version 0.17.30) provides language-specific smarts for Svelte development within various editors by implementing the Language Server Protocol (LSP). It acts as the core engine for features like diagnostics, autocompletion, hover information, formatting, and code actions for Svelte, HTML, CSS/SCSS/LESS, and TypeScript/JavaScript within Svelte components. It is an actively maintained component of the broader `sveltejs/language-tools` monorepo, with frequent patch releases addressing performance improvements and bug fixes, typically on a weekly or bi-weekly cadence. Key differentiators include its deep integration with the Svelte compiler and TypeScript, leveraging `svelte2tsx` for seamless type-checking, and its ability to provide comprehensive language features across multiple embedded languages within `.svelte` files. Unlike many libraries consumed directly via `import`, this package is primarily designed to be run as a separate process by editor extensions (like the official VS Code Svelte extension) or custom LSP clients, offering a robust and extensible foundation for Svelte tooling. Its current stable versions require Node.js >= 18.0.0.
Common errors
-
Cannot find module 'typescript' or its corresponding type declarations.
cause The `typescript` package is a peer dependency but is not installed or not resolvable in the project.fixInstall TypeScript in your project: `npm install -D typescript` or `yarn add -D typescript`. -
The Svelte Language Server process terminated unexpectedly with exit code X.
cause This generic error often indicates an unhandled exception within the server or an incompatible Node.js environment.fixCheck your Node.js version (must be >= 18.0.0). Inspect the server's `stderr` output for more specific error messages if available. -
Could not resolve Svelte files with NodeNext in --incremental/tsgo mode.
cause This was a known bug in older versions related to module resolution strategies in specific TypeScript environments.fixUpdate `svelte-language-server` to version `0.17.30` or newer, as this issue has been addressed in recent patches. Ensure your `tsconfig.json`'s `moduleResolution` is correctly configured. -
TypeScript/JavaScript features (diagnostics, autocompletion) are not working in Svelte files.
cause The TypeScript plugin within the language server might be disabled or misconfigured, or there's an issue with the underlying TypeScript installation.fixEnsure `svelte.plugin.typescript.enable` is set to `true` in your language server configuration (e.g., editor settings). Verify your TypeScript installation and version.
Warnings
- breaking As of `svelte-language-server@0.17.0` (part of `language-tools` v100.1.0), the minimum Node.js version required is 18.0.0. Older Node.js versions will prevent the server from starting.
- gotcha The language server's configuration is highly customizable. Incorrect or conflicting settings, especially those related to TypeScript, CSS preprocessors, or formatting (Prettier), can lead to unexpected behavior or disabled features.
- gotcha The `typescript` package is a peer dependency. If it's not installed in your project or if an incompatible version is present, TypeScript-related language features (diagnostics, autocompletion for TS/JS) will not function correctly.
- gotcha Performance issues in large Svelte projects can arise if the language server is not properly configured with workspace exclusions (e.g., `node_modules`, `dist` directories) or if `svelte-check` is run without `--incremental` flags where applicable.
Install
-
npm install svelte-language-server -
yarn add svelte-language-server -
pnpm add svelte-language-server
Imports
- LSConfigManager
import { LSConfigManager } from 'svelte-language-server' - SvelteDocument
import { SvelteDocument } from 'svelte-language-server' - SveltePlugin
import { SveltePlugin } from 'svelte-language-server'
Quickstart
import { spawn } from 'child_process';
import { resolve } from 'path';
// This quickstart demonstrates how to programmatically launch the Svelte Language Server
// and send an 'initialize' request, as a basic example for building an LSP client.
// In a typical setup, users interact via editor extensions (e.g., VS Code Svelte extension).
const serverExecutable = resolve(__dirname, 'node_modules', 'svelte-language-server', 'bin', 'server.js');
// Spawn the language server process
const lsProcess = spawn('node', [serverExecutable], {
stdio: ['pipe', 'pipe', 'pipe'] // stdin, stdout, stderr pipes
});
let requestId = 1;
function sendLSPRequest(method: string, params: any) {
const request = {
jsonrpc: '2.0',
id: requestId++,
method,
params
};
const jsonRequest = JSON.stringify(request);
const contentLength = Buffer.byteLength(jsonRequest, 'utf8');
const header = `Content-Length: ${contentLength}\r\n\r\n`; // Simplified header
lsProcess.stdin.write(header + jsonRequest);
}
// Listen for responses (simplified, real clients handle streaming and headers)
lsProcess.stdout.on('data', (data) => {
console.log('Language Server Output:', data.toString().trim());
});
lsProcess.stderr.on('data', (data) => {
console.error('Language Server Error:', data.toString().trim());
});
lsProcess.on('close', (code) => {
console.log(`Language Server process exited with code ${code}`);
});
// Send the initial 'initialize' request, crucial for LSP setup
sendLSPRequest('initialize', {
processId: process.pid,
clientInfo: { name: 'Svelte LS Quickstart', version: '1.0' },
rootUri: 'file:///home/user/my-svelte-project', // Replace with actual project root
capabilities: {}, // Define client capabilities as per LSP spec
initializationOptions: { // Pass initial configuration
configuration: {
svelte: {
plugin: {
typescript: { enable: true },
html: { enable: true }
},
// Other Svelte language server specific settings
},
typescript: { /* TypeScript specific settings */ },
javascript: { /* JavaScript specific settings */ },
}
}
});
// In a real application, you would continue to send requests (e.g., didOpen, textDocument/hover)
// and handle responses. For this quickstart, we'll just demonstrate initialization.
// Ensure to properly manage the lifecycle of the child process.
process.on('exit', () => lsProcess.kill()); // Clean up on parent exit