tezvyn:

Svelte Preprocessors: Write in Any Language

AI-drafted, machine-checkedSource: github.comadvanced

A Svelte preprocessor is a translator, converting code like TypeScript or SCSS into plain JS and CSS before compilation. This lets you use advanced tooling in `.svelte` files. The footgun is forgetting to configure it, leading to syntax errors.

WHY IT EXISTS Svelte's compiler is highly optimized, but it's built to understand only three things: JavaScript, CSS, and its own HTML-like template syntax. It doesn't know what to do with TypeScript, SCSS, Less, or Pug. To bridge this gap, Svelte needs a way to transform these other languages into the vanilla JS and CSS it can parse.

THE MENTAL MODEL A preprocessor is a translation step that happens before Svelte's compiler even sees your component code. Think of it like a polyglot assistant. You write in your preferred language (like TypeScript), and the preprocessor translates it into a language Svelte understands (JavaScript) just in time for compilation. This process is transparent to you as a developer once configured.

HOW IT WORKS Svelte provides a preprocess API that hooks into its build process. You specify one or more preprocessors in your svelte.config.js file. When you build your app, Svelte passes the content of your <script>, <style>, and template blocks to these preprocessors. For example, a TypeScript preprocessor takes the content of <script lang="ts">, transpiles it to JavaScript, and returns the result to Svelte. The svelte-preprocess package is a popular choice that conveniently bundles preprocessors for many languages into a single module.

WHEN TO USE IT Use a preprocessor whenever you want to write component logic or styles in a language other than standard JavaScript and CSS. This is standard practice for most production Svelte projects. Common use cases include using TypeScript for type safety, SCSS or Less for nested styles and variables, and PostCSS for autoprefixing CSS.

WHEN NOT TO USE IT If your project is very simple and you are comfortable writing only standard, browser-compatible JavaScript and CSS, you don't technically need a preprocessor. This can simplify your build setup, but it means forgoing the benefits of modern tooling like type systems and advanced CSS syntax.

ONE CANONICAL EXAMPLE A common setup involves using TypeScript and SCSS. In your svelte.config.js, you'll import and configure svelte-preprocess. Then, in a component file, you can write <script lang="ts"> and <style lang="scss">. The preprocessor will automatically handle transpiling the TypeScript to JavaScript and the SCSS to CSS before Svelte compiles the final component, without you needing to run separate build steps.

Read the original → github.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.