By Vivek - November 10, 2020

How to import CSS from node_modules in Svelte

If a package ships its own stylesheet, the cleanest Svelte setup is usually to import that stylesheet once from your app entry point or root layout. This guide shows where to put the import, when a bundler plugin is needed, and how to avoid the common “cannot resolve CSS” errors that happen when styles are imported from node_modules.

Table of Contents

  1. Use a global CSS import
  2. Import package CSS in SvelteKit
  3. Import package CSS in a Rollup Svelte app
  4. Common errors
  5. Related Svelte guides

Use a global CSS import

Use a global import when a package stylesheet is meant to affect the whole app. Examples include Bootstrap, Normalize.css, date picker themes, code editor themes, or a component library’s base stylesheet.

Avoid importing the same package CSS inside many Svelte components. That can duplicate styles, make the cascade harder to reason about, and create order-dependent bugs.

Import package CSS in SvelteKit

In SvelteKit, import package CSS from src/routes/+layout.svelte or from a central CSS file imported by that layout.

<script>
  import 'bootstrap/dist/css/bootstrap.min.css';
  import '../app.css';
</script>

<slot />

If you prefer keeping third-party imports away from Svelte components, create or update src/app.css:

@import 'bootstrap/dist/css/bootstrap.min.css';

Then make sure src/routes/+layout.svelte imports the app stylesheet:

<script>
  import '../app.css';
</script>

Import package CSS in a Rollup Svelte app

Older Svelte projects that use Rollup directly need a CSS plugin so Rollup knows what to do with imported CSS.

  • Install the rollup plugin to process CSS files.
npm install -D rollup-plugin-css-only
  • Configure the plugin in rollup.config.js. This tells Rollup to read CSS imports and write the output to a CSS file.
import css from 'rollup-plugin-css-only';

export default {
   input: 'src/main.js',
   output: {},
   plugins: [
     css({ output: 'public/custom.css' }),
     svelte({};
  • Add the generated CSS file to public/index.html.
<link href="custom.css" />

Common errors

The package path is wrong

Check the package documentation and verify the file exists under node_modules. Some packages expose CSS from dist, while others use styles, themes, or assets.

import 'package-name/dist/package-name.css';

The CSS import runs in the wrong place

If the CSS is global, import it from the root layout or app stylesheet. If it is only needed by one route, a component-level import can work, but make sure the library does not depend on a specific global order.

The package uses assets referenced from CSS

Some CSS files reference fonts or images. SvelteKit and Vite usually handle those URLs, but older Rollup setups may need extra asset handling.