DEV Community

Rahul Barwal
Rahul Barwal

Posted on

Svelte + Typescript + Tailwind

Coming from the Angular world back to Javascript can sometimes feel lackluster. The power of types is too much to resist. Lately, I've been playing around with React and Svelte. To be fair, I am liking Svelte a lot for a small single-page website. Combining these two was a must for me, So here is a post penning down the steps you will need to make your Svelte project run on TypeScript.
Tailwind is a superb CSS framework that can be powerful in bringing your ideas to life in a responsive way 😋.

Installation

Add Svelte project

Clone the svelte repo to your directory with:

npx degit sveltejs/template your-project
Enter fullscreen mode Exit fullscreen mode

Convert it to Typescript

Now change the current directory to your-project and run this command to convert your current JavaScript project to TypeScript, and install packages

cd your-project
node .\scripts\setupTypeScript.js
npm i
Enter fullscreen mode Exit fullscreen mode

Add Tailwind

Install required packages by running the command:

npm i tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
Enter fullscreen mode Exit fullscreen mode

To add tailwind.config.js to your project:

npx tailwindcss init  tailwind.config.js
Enter fullscreen mode Exit fullscreen mode

Setup for your first run

tailwind.config.js

Head over to tailwind.config.js file and add this future property at bottom

future: {
    purgeLayersByDefault: true,
    removeDeprecatedGapUtilities: true,
},
Enter fullscreen mode Exit fullscreen mode

To purge unnecessary classes in production modify purge property to:

purge: {
    content: ["./src/**/*.svelte"],
    enabled: isProduction, // disable purge in dev
},
Enter fullscreen mode Exit fullscreen mode

You won't want purging to be enabled in dev mode, to identify we can use the ROLLUP_WATCH flag.

const isProduction = !process.env.ROLLUP_WATCH;
Enter fullscreen mode Exit fullscreen mode

rollup.config.js

To enable tailwindss during dev and production builds update preprocess property to

preprocess: sveltePreprocess({
        sourceMap: !production,
        postcss: {
          plugins: [require("tailwindcss"), require("autoprefixer")],
    },
}),
Enter fullscreen mode Exit fullscreen mode

App.svelte

You can add this to your App.svelte or optionally this can also be done by creating a new svelte component and then importing it in App.svelte

<style global lang="postcss">
  @tailwind base;
  @tailwind components;
  @tailwind utilities;
</style>
Enter fullscreen mode Exit fullscreen mode

Now you're ready to rock🤘, run your Svelte project with:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Top comments (0)