Published by A&A Agency Updated at:

A&a

  Front-endAngularReactUIJavascriptWebsiteAppUXFirebaseHTML 5SASS developers  

Back

How to setup Svelte application with TypeScript and SCSS

First published:

front-end developers
html
scss
build a website
build an app
coding tutorial
website help
user interface
svelte
typescript
sass

A short guide to setting up Svelte with full support for TypeScript and SCSS

This guide is a simple step by step approach to setting up a Svelte application the way we like it here at A&A, complete with SCSS and TypeScript integration.

If you are not already working with TypeScript and/or SCSS in your front end, I can't recommend it enough. Both syntaxes simplify your code, which not only makes it more readable and organised, but also means you can spend more of your precious time focusing on the most import parts of your application. When you are not chasing variables or debugging undefined arguments in your JavaScript, and when your CSS is not littered with repetition and excess class definitions (or when you don't have to spend time managing these things to avoid them), it provides the opportunity to delve deeper into the possibilities of front-end technology and create more powerful features.

Here's how we start with Svelte.

Setup a new Svelte application

The easiest and best way to get Svelte up and running straight away is to install their master template and work from there. This will bring everything you need into the project, setup the basic folder structure and create your first component for you.

To install the template, you can use the degit package, run with npx. Installing the template this way was the first time I had worked with npx, so for those (like me) that don't know, npx is a package runner; in the same way that npm allows us to install and manage dependencies hosted on the registry, npx allows us to use those packages hosted on the registry, without having to set up local scripts.

Thankfully, you won't need to install anything extra to make use of this tool either – if you already have the latest version of npm installed (5.2.0+), then you will also have npxdegit is a tool used to makes copies of git repositories in their latest state, without the overhead of the git history.

To get started, run this in your terminal (where “my-app” is whatever you want your application to be named):

$ npx degit sveltejs/template my-app $ cd my-app

This should be just about all you need to do to get the most basic Svelte application up and running. From here, you could run npm install and then npm run dev to build your application and view it in a browser. However, as mentioned in the introduction, we prefer writing applications using the syntactical marvels that are TypeScript and Sass. Read on to find out how we add these to our projects.

Adding TS support to a new project

After running the sveltejs/template installation, Svelte can add TypeScript support for us. All we have to do is run this command in the terminal:

$ node scripts/setupTypeScript.js

This script runs almost instantly, so don't be put off if it's complete before your finger has left the return key! Although fast, it should have carried out a number of tasks, including most visibly:

  • Updating your 'rollup.config.js' file to use the typescript plugin and svelte-preprocessor

  • Switching the 'App.svelte' file to use “ts” instead of “js” in the script's type tag

  • Transforming 'main.js' into 'main.ts'

  • Adding a 'tsconfig.json' file

  • Updating your 'package.json' file with a bunch of new packages

We’re almost done. The last task is to actually get all the newly added packages installed. To do this, we simply need to run the npm installer from the terminal:

$ npm i

Then you should be all set. Run the project in dev mode to check there are no errors:

$ npm run dev

If it all builds ok, open it in a browser and check it is loading the content correctly. Change some bits of code and check it updates in the browser (live-reload should change the content automatically upon save).

Adding Sass support

Once you have worked with Sass, it is very difficult to go back to writing plain old CSS! To get it added to a Svelte project is also pretty easy, so if you haven't used it before, it’s worth giving it a go. Firstly, we need to install the necessary Sass processors by running this command in the terminal:

$ npm i sass node-sass autoprefixer postcss -D

Update the 'rollup.config.js' by changing this line:

preprocess: sveltePreprocess()

to include the following additions:

preprocess: sveltePreprocess({ sourceMap: !production, postcss: { plugins: [require('autoprefixer')()] } })

Now you should be able to go into one of your components and change the style tag to include type="scss". The you can do some cool SCSS coding directly in your component, like this:

<style type="scss"> @use '../scss/imports'; main { border: imports.$default-border; h1 { color: imports.$primary-color; } } </style>

Adding TS and Sass support to an existing project

Needless to say, adding support to an existing project means rewriting a lot of your code base anyway, so you are probably best actually starting with a new project, following the steps above, and then porting across your existing files section by section and rebuilding the app in this way. Otherwise, you will likely end up fighting off a barrage of compiler errors, clearing one only to find another until finally all the errors are gone and your app is in pieces anyway. Restarting will overall be a faster, cleaner process and it's also a great opportunity to sanity check your existing application and refactor anything that needs to be, as well as optimizing it now that you have all the added benefits of typescript and Sass available.

That said, if you really want to add this support directly into an existing project, you can still do it pretty easily, you just have to make all the above changes manually. This means for adding Sass support you can just follow the steps above as I already laid them out.

For TypeScript, however, it is not recommended to run setupTypeScript.js on an existing project. By all means you can give it a try on your project, as it will work on a simple project which has not changed much structurally from the master template. Before doing so, it is a good idea to start a new branch, or at least take a copy of your code base so you can easily abandon the changes or roll back. After running the node script to setup typescript (as detailed above), you should notice that the script tag in your 'App.svelte' component now has type="ts" applied to it. You will not, however, find that any of your other components have this change applied. That will be a manual task to switch each file independently. Also, if you moved 'App.svelte' to a different folder (I often nest mine inside a “components” folder), it will not have been updated either. If you made many changes to the 'rollup.config.js' file, you better check that they were not mangled or lost in the switch as well.

The other way to update an existing project is to manually add TypeScript support like we did with Sass. To do it this way, first add the new dependencies:

$ npm i @tsconfig/svelte typescript svelte-preprocess svelte-check @rollup/plugin-typescript -D

Then update the plugins object in 'rollup.config.js' to utilise svelte-preprocess and the typescript plugin:

import sveltePreprocess from 'svelte-preprocess'; import typescript from '@rollup/plugin-typescript'; export default { ..., plugins: [ svelte({ preprocess: sveltePreprocess() }), typescript({ sourceMap: !production, inlineSources: !production }) ] }

You then need to add a 'tsconfig.json' file in the app root:

// tsconfig.json { "extends": "@tsconfig/svelte/tsconfig.json", "compilerOptions": { "typeRoots": ["node_modules/@types"] }, "include": ["src/**/*"], "exclude": ["node_modules/*", "__sapper__/*", "public/*"] }

That’s about it! Your app should now build again, and any component using type="ts" in its script tag should compile successfully and run in the browser without error. As you are converting your JavaScript project into TypeScript, you might find that a whole host of errors now spring out at you when building. These will most likely be type errors and should be quick to fix. Often one type error causes a cascade of error messages during compilation, so don't be put off if your terminal goes wild! Just tackle them one by one and hopefully the list will quickly disappear. Check out our upcoming article on the most common TypeScript compiler errors for more detailed help with this. I will post the link here once it goes live.

If you are looking for a Svelte developer, any other front-end skills, or have any questions at all, feel free to get in touch.

I hope this guide was useful. Thanks for reading.