I-Logs blog

i-logs SRL

How to start a svelte project

Published Mar 31, 2021 (last updated: Apr 29, 2021) by GrΓ©goire Welraeds, managing partner at i-logs. Reading time: 6 minutes

Introduction

This post describes the steps we use at i-logs to setup a new project using Svelte, TailwindCSS, Routify, Roll-up and with TypeScript batteries included.

We won't be using SvelteKit. After a quick check, our conclusion are that, although interesting, the solution is not yet sufficiently mature, particularly for projects in need of intl18 support. If you plan to use SvelteKit, follow these instructions

We will not introduce you to these tools. After all you know why you are here.

We started following these instructions but we noticed a few steps were missing or are outdated. This the main reason of this post, a note to ourself which might be useful to others.

0. Before we begin

We are assuming node, npm and npx tools are installed on your system. Installing these tools is out of the scope of this document. You may of course use alternate tools (like yarn), provided you know how to use them.

1. bootstrap Svelte

First, create a new project with the svelte template. Our project is called app (How dare we?)

npx degit sveltejs/template app
cd app/
npm install

If the app folder already exists (let say, you have cloned an empty git repository) you may use the --force option with the npx command because otherwise the template will not be installed.

Starting from here, all further instructions are executed in the app/ folder.

2. Install svelte i18n

In a country with multiple official languages like Belgium, support for translation is very often mandatory. Hopefully, this steps is straightforward:

npm install svelte-i18n

If you need i18n support in your svelte app, I strongly recommand you to read this blog post from Lokalise. It is the most complete guide we have found.

3. Typescript support

Starting in July 2020, Svelte <3 Typescript. It provides a nice development experience. It also scales beautifully to larger Svelte code bases β€” regardless of whether you use TypeScript or JavaScript.

node scripts/setupTypeScript.js

the setupTypeScript.js script modifies the project to support TS code in .svelte files like:

  <script lang="ts">
  	export let name: string;
  </script>

As well as validating the code for CI.

In a nutshell, what this script does:

  1. update dependencies in the package.json file (adding typescript, svelte-preprocess and svelte-check)
  2. rename src/main.js to src/main.ts and transform the javascript code to typescript
  3. update the rollup configuration file to add typescript as a preprocessor
  4. creates a basic tsconfig file.
  5. remove itself.

Once the script has completed its tasks, you are invited to re-run the dependency manager to get started:

npm install

4. Install Tailwind CSS

Now that our standard svelte project is ready, time to add support for tailwind css (version > 2.0). We will also add in autoprefixer and postcss-nesting.

This step slightly differs from the original post to avoid an error with support for PostCSS 8 (which we've faced):

npm install -D svelte-preprocess tailwindcss@latest postcss@latest autoprefixer@latest postcss-nesting

Looking in the package.json file, make sure postcss version is above 8.

Next, add a tailwind.config.js file at the root of the project, use your favorite Javascript editor:

const isProduction = !process.env.ROLLUP_WATCH;

module.exports = {
    plugins: [],
    purge: {
        content: [
            "./src/**/*.svelte",
            "./src/**/*.html"
        ],
		// this is for extracting Svelte `class:` syntax but is not perfect yet, see below
        defaultExtractor: content => {
            const broadMatches = content.match(/[^<>"'`\s]*[^<>"'`\s:]/g) || []
            const broadMatchesWithoutTrailingSlash = broadMatches.map(match => _.trimEnd(match, '\\'))
            const matches = broadMatches
                .concat(broadMatchesWithoutTrailingSlash)
            return matches
        },
        enabled: isProduction // disable purge in dev
    },
};

Next, let's add these packages as postcss plugins. Open the file rollup.config.js and

  1. At the top of the file, just after the import section, add the following line:

    const production = !process.env.ROLLUP_WATCH;
    
  2. navigate to the svelte plugins section, and add the following lines:

    plugins: [
        svelte({
          // etc...
          preprocess: sveltePreprocess({
    	// https://github.com/kaisermann/svelte-preprocess/#user-content-options
    	sourceMap: !production,
    	postcss: {
    	  plugins: [
    	     require("tailwindcss"), 
    	     require("autoprefixer"),
    	     require("postcss-nesting")
    	  ],
    	},
          }),
        }),
      ]
    
    

In the above example, we have used the ROLLUP_WATCH environment variable, but you are free to select another name.

Finally, we want to add the tailwind includes in our app. You'll want to put these includes at a reasonably high level, say App.svelte or Layout.svelte component that will be included in every page of your site.

<style global lang="postcss">
        @tailwind base;
        @tailwind components;

        @tailwind utilities;

</style>

5. Conclusion

The process is rather straigthforward providing you know what you are doing :). You are now good to go, start your development server with npm run devto make sure, everything went smoothly:


> svelte-app@1.0.0 dev /path/to/the/folder/app
> rollup -c -w

rollup v2.44.0
bundles src/main.ts β†’ public/build/bundle.js...
LiveReload enabled
created public/build/bundle.js in 21.1s

[2021-03-31 11:43:59] waiting for changes...

> svelte-app@1.0.0 start /path/to/the/folder/app
> sirv public --no-clear "--dev"


  Your application is ready~! πŸš€

  - Local:      http://localhost:5000
  - Network:    Add `--host` to expose

────────────────── LOGS ──────────────────

Happy Coding !

6. Additionnal notes