A Svelte preprocessor with support for: PostCSS, SCSS, Less, Stylus, Coffeescript, TypeScript and Pug.
npm install -D svelte-preprocess
The preprocessor module installation is up to the developer.
babel
:npm install -D @babel/core @babel/preset-...
coffeescript
:npm install -D coffeescript
typescript
:npm install -D typescript
postcss
:npm install -D postcss postcss-load-config
less
:npm install -D less
sass
:npm install -D node-sass
ornpm install -D sass
pug
:npm install -D pug
stylus
:npm install -D stylus
Note: If you want to load your postcss
configuration from a external file, make sure to also install postcss-load-config
.
Add vue-like support for defining your markup between a <template>
tag. The tagname can be customized to something like markup
for example. See #options.
Note: only for auto preprocessing
<template>
<div>Hey</div>
</template>
<style></style>
<script></script>
<template src="./template.html"></template>
<script src="./script.js"></script>
<style src="./style.css"></style>
Add a global
attribute to your style
tag and instead of scoping the css, all of its content will be interpreted as global style.
<style global>
div {
color: red;
}
</style>
Note1: needs postcss to be installed Note2: if you're using it as a standalone processor, it works best if added to the end of the processors array.
Current supported out-of-the-box preprocessors are SCSS
, Stylus
, Less
, Coffeescript
, TypeScript
, Pug
, PostCSS
, Babel
.
<template lang="pug">
div Posts
+each('posts as post')
a(href="{post.url}") {post.title}
</template>
<script lang="typescript">
// Compatible with Svelte v3...
export const hello: string = 'world';
</script>
<script type="text/coffeescript">
# ...and v2!
export default
methods:
foo: () ->
console.log('Hey')
</script>
<style src="./style.scss"></style>
<!-- Or -->
<style src="./style.styl"></style>
<!-- Or -->
<style lang="scss">
$color: red;
div {
color: $color;
}
</style>
<!-- Or -->
<style type="text/stylus">
$color=reddivcolor: $color;
</style>
svelte-preprocess
allows you to run your component code through babel
before sending it to the compiler, allowing you to use new language features such as optional operators and nullish coalescing. However, note that babel
should transpile your component code to the javascript version supported by the Svelte compiler, so ES6+.
For example, with @babel/preset-env
your config could be:
import preprocess from 'svelte-preprocess'
...
preprocess: preprocess({
babel: {
presets: [
[
'@babel/preset-env',
{
loose: true,
// No need for babel to resolve modules
modules: false,
targets: {
// ! Very important. Target es6+
esmodules: true,
},
},
],
],
},
});
...
Note: If you want to transpile your app to be supported in older browsers, you must run babel from the context of your bundler.
// rollup.config.js
import svelte from 'rollup-plugin-svelte';
import autoPreprocess from 'svelte-preprocess'
import { scss, coffeescript, pug } from 'svelte-preprocess'
export default {
...,
plugins: [
svelte({
/**
* Auto preprocess supported languages with
* '<template>'/'external src files' support
**/
preprocess: autoPreprocess({ /* options */ })
/**
* It is also possible to manually enqueue
* stand-alone processors
* */
preprocess: [
pug({ /* pug options */ }),
scss({ /* scss options */ }),
coffeescript({ /* coffeescript options */ })
]
})
]
}
...
module: {
rules: [
...
{
test: /\.(html|svelte)$/,
exclude: /node_modules/,
use: {
loader: 'svelte-loader',
options: {
preprocess: require('svelte-preprocess')({ /* options */ })
},
},
},
...
]
}
...
Sapper has two build configurations, one for the client bundle and one for the server. To use svelte-preprocess
with Sapper, you need to define it on both configurations.
// ...
import sveltePreprocess from 'svelte-preprocess';
const preprocess = sveltePreprocess({
postcss: true,
// ...
});
export default {
client: {
plugins: [
svelte({
preprocess,
// ...
}),
},
server: {
plugins: [
svelte({
preprocess,
// ...
}),
],
},
};
svelte-vscode needs to know how its (svelte) language server should preprocess your files. This can be achieved by creating a svelte.config.js
file at the root of your project which exports a svelte options object (similar to svelte-loader
and rollup-plugin-svelte
).
Example:
// svelte.config.js
const sveltePreprocess = require('svelte-preprocess');
module.exports = {
preprocess: sveltePreprocess({
// ...svelte-preprocess options
}),
// ...other svelte options
};
Tip: this file can be imported in your bundle config instead of having multiple svelte configurations lying around.
svelte-preprocess
can be used in two ways: auto preprocessing and with stand-alone processors.
In auto preprocessing mode, svelte-preprocess
automatically uses the respective preprocessor for your code based on your type="..."
or lang="..."
attributes. It also handles the <template>
tag for markup, external files and global styling. It's as simple as importing the module and executing the default exported method.
const sveltePreprocess = require('svelte-preprocess')
...
{
/* svelte options */
...,
preprocess: sveltePreprocess({ /* options */ }),
}
...
Svelte v3 has added support for multiple processors, so it's also possible to use svelte-preprocess
with other preprocessors:
const sveltePreprocess = require('svelte-preprocess')
const { mdsvex } = require('mdsvex')
...
{
/* svelte options */
...,
preprocess: [
sveltePreprocess({ /* svelte-preprocess options */ }),
msdvex({ /* mdsvex options */ })
],
}
...
In case you want to manually configure your preprocessing step, svelte-preprocess
exports these named processors:
pug
coffeescript
orcoffee
less
scss
orsass
stylus
postcss
globalStyle
- transform<style global>
into global styles.
import { scss, coffeescript, pug, globalStyle } from 'svelte-preprocess';
svelte.preprocess(input, [pug(), coffeescript(), scss(), globalStyle()]);
Every processor accepts an option object which is passed to its respective underlying tool.
import { scss, postcss } from 'svelte-preprocess';
svelte.preprocess(input, [
scss(),
postcss({
plugins: [
require('autoprefixer')({
browsers: 'last 2 versions',
}),
],
}),
]);
Note: there's no built-in support for <template> tag when using standalone processors.
svelte-preprocess
in auto-processing mode can receive an options object.
const svelte = require('svelte');
const sveltePreprocess = require('svelte-preprocess');
const options = {
/**
* Define which tag should `svelte-preprocess` look for markup content.
*
* This is only used if you desire to define your markup between this tag
* or to import it from a external file.
*
* The example below means your markup can be defined inside a `<markup>` tag.
**/
markupTagName: 'markup',
/**
* Extend the default language alias dictionary.
* Each entry must follow: ['alias', 'languageName']
*/
aliases: [
/**
* Means
* <... src="./file.cst"> or
* <... lang="cst"> or
* <... type="text/customLanguage">
* <... type="application/customLanguage">
* will be treated as the language 'customLanguage'
*/
['cst', 'customLanguage'],
],
preserve: [
/**
* Using the same matching algorithm as above, don't parse,
* modify, or remove from the markup, tags which match the
* language / types listed below.
* **/
'ld+json',
],
/** Disable a language by setting it to 'false' */
scss: false,
/** Pass options to the default preprocessor method */
stylus: {
paths: ['node_modules'],
},
/**
* Post process css with PostCSS by defining 'transformers.postcss' property,
* either pass 'true' to activate PostCSS transforms and use the `postcss.config.js`
*/
postcss: true,
/** or pass an object with postcss plugins and their options directly. */
postcss: {
plugins: [require('autoprefixer')({ browsers: 'last 2 versions' })],
},
typescript: {
/**
* Optionally specify the directory to load the tsconfig from
*/
tsconfigDirectory: './configs',
/**
* Optionally specify the full path to the tsconfig
*/
tsconfigFile: './tsconfig.app.json',
/**
* Optionally specify compiler options.
* These will be merged with options from the tsconfig if found.
*/
compilerOptions: {
module: 'es2015',
},
/**
* Type checking can be skipped by setting 'transpileOnly: true'.
* This speeds up your build process.
*/
transpileOnly: true,
},
/** Use a custom preprocess method by passing a function. */
pug({ content, filename }) {
const code = pug.render(content);
return { code, map: null };
},
/** Add a custom language preprocessor */
customLanguage({ content, filename }) {
const { code, map } = require('custom-language-compiler')(content);
return { code, map };
},
};
svelte.preprocess(input, sveltePreprocess(options));
Since typescript
is not officially supported by svelte
for its template language, svelte-preprocess
only type checks code in the <script></script>
tag.
Some of Svelte's template syntax is invalid in pug
. svelte-preprocess
provides some pug mixins to represent svelte's {#...}{/...}
blocks: +if()
, +else()
, +elseif()
, +each()
, +await()
, +then()
, +catch()
, +debug()
.
ul
+if('posts && posts.length > 1')
+each('posts as post')
li
a(rel="prefetch" href="blog/{post.slug}") {post.title}
+else()
span No posts :c
Pug encodes everything inside an element attribute to html entities, so attr="{foo && bar}"
becomes attr="foo && bar"
. To prevent this from happening, instead of using the =
operator use !=
which won't encode your attribute value:
button(disabled!="{foo && bar}")
If you have configured svelte-preprocess
to use some kind of preprocessor and svelte-vscode
is displaying errors like it's ignoring your preprocess configuration, that's happening because svelte-vscode
needs to know how to preprocess your components. svelte-vscode
works by having a svelte compiler running on the background and you can configure it by creating a svelte.config.js
file on your project's root. Please check this document With Svelte VS Code section.
If you have a medium-to-big project, the typescript processor might start to get slow. If you already have an IDE type checking your code, you can speed up the transpilation process by setting transpileOnly
to true
:
const preprocess = require('svelte-preprocess')
...
{
...svelteOptions,
preprocess: preprocess({
typescript: {
// skips type checking
transpileOnly: true,
compilerOptions: {
...
},
},
})
}
...