You too can ace that coding interview
Get my guide for free
July 07, 2020

How to import CSS files to Svelte

Learn how to import CSS from node_modules into Svelte components

Here’s how you import a CSS file from node_modules in a Svelte component. This post assumes you’re bundling your app with Rollup.

  1. Install the rollup plugin to process CSS files.
npm i rollup-plugin-css-only
  1. Configure the plugin in rollup.config.js. This will tell rollup to read the CSS imports and write them in a file called vendor.css.
+ import css from 'rollup-plugin-css-only';

export default {
  input: 'src/main.js',
  output: { ... },
  plugins: [
+   css({ output: 'public/build/vendor.css' }),
    svelte({
      ...
    }),
    ...
};
  1. Add the CSS file to index.html.
  <html lang="en">
  <head>
	...
+	<link rel='stylesheet' href='/build/vendor.css'>
    ...
    <script defer src='/build/bundle.js'></script>

  </head>

  <body>
  </body>
  </html>
  1. Import your CSS file in App.svelte. It’s not necessary to use the full path to node_modules.
 <script>
+   import 'notyf/notyf.min.css';
	export let name;
 </script>

 <main> <h1> Hello {name}! </h1> </main>

 <style> h1 { color: #ff3e00; } </style>
Logo

I'm Carlos Roso. I'm a Software Engineer and digital nomad at Toptal. Previously Software Architect at Crossover. In love with open source and design.

More about me
Join the newsletter

I write about remote work, software and personal growth. Subscribe to enjoy my articles every once in a while.