Initialize & Configure

Learn how to initialize Tailwind CSS and configure it to make it work with Svelte/Sapper.

We'll cover the following

Initializing and configuring

Create a new branch:

git switch -c add-tailwind-css

First things first, let’s install the necessary NPM packages and configure a few things to make Tailwind work with Svelte/Sapper.

Run the following command in the services/web directory:

npm i -D tailwindcss svelte-preprocess postcss autoprefixer

npm install

We have executed npm install to sync packages in package.json and package-lock.json.

Next, let’s use Tailwind’s initialization script:

./node_modules/.bin/tailwindcss init

This created a tailwind.config.js file with empty defaults. We want to update the purge property to match the following:

purge: {
  content: ["./src/**/*.svelte"],
  options: {
    whitelistPatterns: [/svelte-/],
  },
},

Tailwind CSS comes with a large number of CSS classes by default. This is great for development as we can run the dev server, open the browser’s developer tools, and add/remove Tailwind CSS classes at runtime. The drawback is that the CSS file is huge! So, we tell Tailwind in the above-mentioned purge property to scan our *.svelte files and look for all the Tailwind CSS classes we use. Any other default Tailwind CSS classes are removed from the final CSS bundle.

We also want to keep any svelte- class names. Hence, we whitelist them to tell the purge process to ignore these class names.

The final step to configure Tailwind CSS for our Sapper web application is to update the services/web/rollup.config.js file.

Import the following two packages:

import sveltePreprocess from "svelte-preprocess";
import tailwindcss from "tailwindcss";

Create the Svelte preprocessor options above the export default { line:

const sveltePreprocessOptions = sveltePreprocess({
  postcss: {
    plugins: [tailwindcss],
  },
});
  • postcss preprocessor will compile all the Tailwind CSS files.

The final change in the services/web/rollup.config.js file is to tell Svelte to use the preprocessor. This needs to be done for both the client and server properties in the default export!

Add the following to the two svelte({}) function calls:

preprocess: sveltePreprocessOptions,

To make sure Tailwind CSS purges classes when we export the Sapper web application, we need to set the NODE_ENV variable to production during the export. We can do this in the services/web/package.json file by changing the export script to the following:

"export": "NODE_ENV=production sapper export ./firebase/public --legacy",

Instructions: Use nano to open the files in the terminal editor.

Get hands-on with 1200+ tech skills courses.