DEV Community

Cover image for Sveltekit Vite with Tailwind 2
dan
dan

Posted on • Updated on

Sveltekit Vite with Tailwind 2

svelte@next with postcss and tailwind

UPDATE :

5.update to SvelteKit Vite, all work. This post outdate and will not maintain anymore, check the repo
4.add demo
3.make run build export static build/ directory
2.fix run build error
1.fix huge error

S T O P

Pump the brakes! A little disclaimer...

svelte@next is not ready for use yet. It definitely can't
run your apps, and it might not run at all.

We haven't yet started accepting community contributions,
and we don't need people to start raising issues yet.

Given these warnings, please feel free to experiment, but
you're on your own for now. We'll have something to show
soon.
Enter fullscreen mode Exit fullscreen mode

Sapper v1 will never be released, instead Svelte is being developed further. For more information, please check out the jessenkinner post at dev.to : Sapper is dead, what is next in Svelte?

However, that didn't stop me from trying it wholeheartedly.

By the way, I just got to know pnpm and was very happy to know and use it. So I'm going to use pnpm instead of npm or yarn, although they both have the same use.

Create Svelte project

for now, you can run this command in your terminal, assuming you have pnpm installed :

pnpm init svelte@next svelte-next
cd svelte-next
pnpm i
Enter fullscreen mode Exit fullscreen mode

Where svelte-next is the name of your project directory. You can choose if you want to use typescript or not.

Before going any further, we can ensure that the current version is "ok" to develop by running the command below and accessing localhost:3000 in the browser.

pnpm run dev
Enter fullscreen mode Exit fullscreen mode

If you got error like this

Error: NOT_FOUND
    at Object.loadUrl (C:\Users\hp\www\sveltest\node_modules\.pnpm\snowpack@3.0.0-rc.2\node_modules\snowpack\src\commands\dev.ts:607:13)
    at C:\Users\hp\www\sveltest\node_modules\.pnpm\@sveltejs\kit@1.0.0-next.15\node_modules\@sveltejs\kit\src\api\dev\index.js:167:14
Enter fullscreen mode Exit fullscreen mode

it seems like there problem in the snowpack configuration, so edit plugins line to like this

    plugins: [
        [
            "@snowpack/plugin-svelte",
            {
                compilerOptions: {
                    hydratable: true
                }
            }
        ],
        '@snowpack/plugin-typescript'
    ],
Enter fullscreen mode Exit fullscreen mode

stop and rerun the dev server

Setting up the preprocess

If you are not using typescript, then you need to add the preprocess manualy by run this command

pnpm i -D svelte-preprocess
Enter fullscreen mode Exit fullscreen mode

Then apply the preprocess to svelte add PostCSS to it

// svelte.config.js
const sveltePreprocess = require('svelte-preprocess');
module.exports = {
    // Consult https://github.com/sveltejs/svelte-preprocess
    // for more information about preprocessors
    preprocess: [
        sveltePreprocess({
            defaults: {
                script: 'typescript',
                style: 'postcss',
            },
            postcss: true
        }),
    ],
    kit: {
        // By default, `npm run build` will create a standard Node app.
        // You can create optimized builds for different platforms by
        // specifying a different adapter
        adapter: '@sveltejs/adapter-node',

        // hydrate the <div id="svelte"> element in src/app.html
        target: '#svelte'
    }
};
Enter fullscreen mode Exit fullscreen mode

The default object property that defines the default languages of your components. so the configuration above makes TypeScript the default language, removing the need of adding lang="ts" to script tags and lang="postcss" to style tags.

Add PostCSS and Tailwind

pnpm add -D @snowpack/plugin-postcss postcss postcss-cli postcss-load-config postcss-preset-env
pnpm add -D tailwindcss autoprefixer cssnano
Enter fullscreen mode Exit fullscreen mode

Because svelte@next still in development, maybe you wont to bring it to production, you may just skip autoprefixer or cssnano if you don't need them.

I just use postcss-preset-env for nesting, you can use other plugin like postcss-nesting or else.

Setting up PostCSS

Edit the Snowpack Configuration file

// snowpack.config.js
// Consult https://www.snowpack.dev to learn about these options
module.exports = {
    extends: '@sveltejs/snowpack-config',
    plugins: [
        [
            '@snowpack/plugin-build-script',
            {
                cmd: "postcss",
                input: [".css", ".pcss"],
                output: [".css"],
            }
        ],
        [
            "@snowpack/plugin-svelte",
            {
                compilerOptions: {
                    hydratable: true
                }
            }
        ],
        '@snowpack/plugin-typescript'
    ],
    mount: {
        'src/components': '/_components'
    },
    alias: {
        $components: './src/components'
    }
};

Enter fullscreen mode Exit fullscreen mode

Create PostCSS configuration file in the project's root folder. Shomething like this.

// postcss.config.js
const mode = process.env.NODE_ENV;
const dev = mode === "development";

module.exports = {
    plugins: [
        require('postcss-preset-env')({stage: 1}),
        require("tailwindcss"),
        require("autoprefixer"),

        !dev && require("cssnano")({
            preset: "default",
        }),
    ],
};
Enter fullscreen mode Exit fullscreen mode

Setting up Tailwind

Run this command

npx tailwind init
Enter fullscreen mode Exit fullscreen mode

Edit Tailwind configuration

// taiwind.config.js
const { tailwindExtractor } = require("tailwindcss/lib/lib/purgeUnusedStyles");

module.exports = {
    purge: {
        content: [
            "./src/**/*.html",
            "./src/**/*.svelte"
        ],
        options: {
            defaultExtractor: (content) => [
                ...tailwindExtractor(content),
                ...[...content.matchAll(/(?:class:)*([\w\d-/:%.]+)/gm)].map(([_match, group, ..._rest]) => group),
            ],
            keyframes: true,
        },
    },
    darkMode: 'class',
    theme: {
        extend: {},
    },
    variants: {
        extend: {},
    },
    plugins: [],
};
Enter fullscreen mode Exit fullscreen mode

the tailwindExtractor is for future purpose, so you can use class: directive

Tailwind ready to use

Create src\routes\global.pcss

@tailwind base;
@tailwind components;
@tailwind utilities;

Enter fullscreen mode Exit fullscreen mode

then use it on src\routes\$layout.svelte

<script>
    import './global.pcss';
</script>

<slot/>
Enter fullscreen mode Exit fullscreen mode

on the src\routes\index.svelte

<script>
    import Counter from '$components/Counter.svelte';
</script>

<main>
    <h1 class="uppercase text-5xl font-extrabold my-16">Hello world!</h1>

    <Counter/>
    <p>Visit the <a href="https://svelte.dev">svelte.dev</a> to learn how to build Svelte apps.</p>
</main>

<style>
  main {
    @apply px-8 py-16 mx-auto max-w-5xl text-center;
  }

  * + * {
    @apply mb-0 mt-4;
  }

  p {
    @apply text-xl;
  }
</style>
Enter fullscreen mode Exit fullscreen mode

The boileplate

Sveltekit with Tailwind

If you want to try ready to use boiler plate I made with dark mode toggle theme, you can check my reposistory here

UPDATE :

  • to generate static site you can deploy in netlify, just run build command, i already update the repo
  • Live Demo

Still learning to write post in English. Please be advised.

comment if you find another error

thanks

Top comments (36)

Collapse
 
eugenioclrc profile image
Eugenio

I think this its only working with the initial kit version, with the latest version its not working :(
I try different things and always is the same error;
Error: NOT_FOUND
at Object.loadUrl (....../svelte-next/node_modules/.pnpm/snowpack@3.0.0-rc.2/node_modules/snowpack/src/commands/dev.ts:607:13)
at ....../svelte-next/node_modules/.pnpm/@sveltejs/kit@1.0.0-next.14/node_modules/@sveltejs/kit/src/api/dev/index.js:165:14

Collapse
 
acidlake profile image
Jeremias Nunez

it was not working for my at first also, but i manage to get it working on my way, here are my config.

first create a project like you normal do pnpm init svelte@next project-name
then edit your files as the one that im using, after that run pnpm i, and wait for the install to finish after that, pnpm run dev and done.

URL: codeshare.io/5XbRjj

Collapse
 
eugenioclrc profile image
Eugenio

with this change the preload function hook its not working

Collapse
 
eugenioclrc profile image
Eugenio

well that did work! buuut, know the i18n is broken :*(

Error: [svelte-i18n] Cannot format a message without first setting the initial locale.
:(

Thread Thread
 
acidlake profile image
Jeremias Nunez

that's some error regarding svelte-i18n follow this instructions to make it work github.com/kaisermann/svelte-i18n/...

Collapse
 
dansvel profile image
dan

thanks, i already update the post for this error,,

Collapse
 
esgabo profile image
Gabriel Espinel

Hi, Dan. This is very helpful.

Have you experienced an issued with the "hover:underline" in the index.svelte file?. I'm getting an error

Build Error: @snowpack/plugin-svelte
Semicolon or block is expected (31:32)
29: }
30: a {
31: @apply text-indigo-600 hover:underline;
^
32: }

It seems it's not able to process the CSS correctly. Once I remove that, it works.

Collapse
 
dansvel profile image
dan

hm,, it's hard because you don't use the code style,,

i think it would be the

a {
  @apply text-indigo-600 hover: underline; /* use space after colon will make error in preprocess */
  @apply text-indigo-600 hover:underline;
}
Enter fullscreen mode Exit fullscreen mode
div {
  @apply md: px-4; /* not works */
  @apply md:px-4; /* work fine */
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
esgabo profile image
Gabriel Espinel

I think I found the issue.
The file svelte.config does not have the ´postcss: true´ in the repo
github.com/dansvel/sveltekit-types...

However, it does instruct that property in this current page. Once I applied that config, it worked fine. Thanks.

You may want to apply that fix in the repo as well.

Thread Thread
 
dansvel profile image
dan

aw man,, thanks,, i already update the file,,

i still in experiment to make the repo as simple as possible,,

Collapse
 
esgabo profile image
Gabriel Espinel

Thanks. I'm sorry about the format. I didn't make any change to your code, I simply clone the repo and it didn´t worked for me as is. The code doesn´t have any space.

Collapse
 
mzaini30 profile image
Zen

I try Svelte Kit today and get this error:

Error: No element indexed by 0
    at ArraySet$2.ArraySet_at [as at] (D:\zen\latihan-svelte-kit\node_modules\.pnpm\vite@2.0.5\node_modules\vite\dist\node\chunks\dep-e0f09032.js:24278:9)
    at BasicSourceMapConsumer.<anonymous> (D:\zen\latihan-svelte-kit\node_modules\.pnpm\vite@2.0.5\node_modules\vite\dist\node\chunks\dep-e0f09032.js:25193:67)
    at Array.map (<anonymous>)
    at BasicSourceMapConsumer.SourceMapConsumer_eachMapping [as eachMapping] (D:\zen\latihan-svelte-kit\node_modules\.pnpm\vite@2.0.5\node_modules\vite\dist\node\chunks\dep-e0f09032.js:25192:14)
    at merge (D:\zen\latihan-svelte-kit\node_modules\.pnpm\vite@2.0.5\node_modules\vite\dist\node\chunks\dep-e0f09032.js:26656:18)
    at ssrTransform (D:\zen\latihan-svelte-kit\node_modules\.pnpm\vite@2.0.5\node_modules\vite\dist\node\chunks\dep-e0f09032.js:61382:15)
    at transformRequest (D:\zen\latihan-svelte-kit\node_modules\.pnpm\vite@2.0.5\node_modules\vite\dist\node\chunks\dep-e0f09032.js:61650:48)
    at async instantiateModule (D:\zen\latihan-svelte-kit\node_modules\.pnpm\vite@2.0.5\node_modules\vite\dist\node\chunks\dep-e0f09032.js:67994:10)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dansvel profile image
dan

currently you cannot use any postcss or typescript. But you could init a project with no typescript and and only css and you should also get the dev server running. This is the tracking issue as far as I know:

github.com/vitejs/vite/issues/2391

Collapse
 
mzaini30 profile image
Zen

Thanks

Collapse
 
quantuminformation profile image
Nikos

tried to run dev

(node:92442) ExperimentalWarning: The ESM module loader is experimental.

Listening on localhost:3000
Error: No element indexed by 0
at ArraySet$2.ArraySet_at as at
at BasicSourceMapConsumer. (/U

I'll stop now)

Collapse
 
dansvel profile image
dan

for now, the latest version of svelte kit is using esm, and vite as builder and everything is broken,,

if you want to try sveltekit work,, you need specify the version,, maybe nex.29 or next.34 in your package.json file,,

for more information, check sk-incognito.vercel.app/learn/what...

the maintaner of sveltekit said, better to work with sapper, coz migrating will easy,,

Collapse
 
quantuminformation profile image
Nikos

thx

 
dansvel profile image
dan

oh,, sorry,,

i think i know why it doesn't export index.html is because in svelte.config.js the adapter is node,

try to install @sveltejs/adapter-static and change the svelte.config.js adapter to static

Collapse
 
dansvel profile image
dan • Edited

@avorona , I think I've found the problem, I think it's because svelte compiles all files into .js ,, soglobal.pcss becomes global.js ,, or index.pcss or other name

what we can do to run the run build without problems,

  • rename the file global.pcss toGlobalStyle.svelte
  • edit the contents of GlobalStyle.svelte to be something like this
<style global>
/* preprocessing css goes here */
</style>
Enter fullscreen mode Exit fullscreen mode
  • and in the $layout.svelte
<script>
  // import './global.pcss'
  import GlobalStyle from './GlobalStyle.svelte'

  // other code
</script>

<GlobalStyle/> <!-- call the component  -->
<main>
  <slot/>
</main>
Enter fullscreen mode Exit fullscreen mode

do the run build,, and,, BOOM!!! no error

please CMIIW

Collapse
 
eugenioclrc profile image
Eugenio

Why not inside the $layout.svelte?

Collapse
 
mhatvan profile image
Markus Hatvan

As far as I know from the Svelte Discord channel, running it is broken right now for Typescript, for JavaScript it should work.

For Typescript, a workaround is to add

"resolutions": {
  "snowpack": "2.17.0"
}
Enter fullscreen mode Exit fullscreen mode

to the package.json

Collapse
 
dansvel profile image
dan • Edited

I still haven't found a way ,,

from npmjs.com/package/@sveltejs/kit

This project aims to replicate Sapper's functionality in its entirety, minus building for deployment (which can be handled by 'adapters' that do various opinionated things with the output of snowpack build).

Collapse
 
babichjacob profile image
Jacob Babich

Hi dan, it may help to clarify that "$layout.svelte on root" means src/routes/$layout.svelte and to fix the typo in "Create src\routes.pcss" to src/routes/global.pcss

Collapse
 
dansvel profile image
dan

very thanks,

i write it in late night, like 2.30 am,,

Collapse
 
eugenioclrc profile image
Eugenio

I think now the preload funcition tis not working;

export async function preload({ host, path, params, query }, session) {
console.log('working')
}

Collapse
 
dansvel profile image
dan

i think it's sveltekit problem different from sapper,, need to wait for documentation for more

Collapse
 
eugenioclrc profile image
Eugenio

preload function has been renamed to load;
twitter.com/Rich_Harris/status/134...

 
dansvel profile image
dan

i found the way to generate build/ directory,,

just run npx svelte-kit adapt after you run build command

Collapse
 
avorona profile image
Vitalii

Thanks, dan!
adding a @snowpack/plugin-svelte at the initial kit version helped me run the project

Collapse
 
dansvel profile image
dan

the problem i face is, when i try to run build on fresh install project it's always give me error.

have you tried too?

Collapse
 
avorona profile image
Vitalii • Edited
Collapse
 
dansvel profile image
dan

thanks for mention it, i really forgot about snowpack.config.js i already update it,,

Collapse
 
tw1t611 profile image
tw1t611 • Edited

same for me, was anyone able to get this to work?

Collapse
 
acidlake profile image
Jeremias Nunez

check my reply above to Dan, i manage to get it working

Collapse
 
dansvel profile image
dan

i made more update to fix more things,, hope that will help,,