chapter twenty

20 Preprocessors

 

This chapter covers:

  • Custom preprocessing
  • Using svelte-preprocess and its auto-preprocessing mode
  • Using Sass instead of CSS
  • Using TypeScript instead of JavaScript
  • Using Markdown instead of HTML
  • Using multiple preprocessors
  • Image compression as a preprocessing step

By default Svelte and Sapper only support using JavaScript, HTML, and CSS. Preprocessors enable the use of alternate syntaxes for these files that can simplify writing the code and/or provide additional features not otherwise present.

This chapter assumes that readers interested in adding preprocessing will have some familiarity with Sass, TypeScript, and Markdown. Readers may have also heard of less popular options including CoffeeScript, Pug, Less, PostCSS, and Stylus, but knowing about those is less important because no examples of using them are shown here.

Svelte apps can optionally configure the use of preprocessors that transform the content of .svelte files before they are passed to the Svelte compiler. This is typically specified in the configuration file for the bundler being used, such as Rollup or Webpack.

Examples of preprocessing include:

  1. Converting Sass syntax to CSS
  2. Compiling TypeScript code to JavaScript
  3. Converting Markdown or Pug syntax to HTML
  4. Custom search and replace

Many npm packages can be used to implement preprocessing. Some examples are identified in the sections below.

20.1  Custom preprocessing

20.1.1  Using Webpack

20.2  svelte-preprocess

20.2.1  Auto-preprocessing mode

20.2.2  External files

20.2.3  Global styles

20.2.4  Using Sass

20.2.5  Using TypeScript

20.2.6  VS Code tip

20.3  Using Markdown

20.4  Using multiple preprocessors

20.5  Image compression

20.6  Summary