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.
- Install the rollup plugin to process CSS files.
npm i rollup-plugin-css-only
- Configure the plugin in
rollup.config.js
. This will tell rollup to read the CSS imports and write them in a file calledvendor.css
.
+ import css from 'rollup-plugin-css-only';
export default {
input: 'src/main.js',
output: { ... },
plugins: [
+ css({ output: 'public/build/vendor.css' }),
svelte({
...
}),
...
};
- 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>
- Import your CSS file in
App.svelte
. It’s not necessary to use the full path tonode_modules
.
<script>
+ import 'notyf/notyf.min.css';
export let name;
</script>
<main> <h1> Hello {name}! </h1> </main>
<style> h1 { color: #ff3e00; } </style>
I'm Carlos Roso. I'm a Production Engineer at Meta. Former SDE at Amazon. Ex digital nomad at Toptal and Crossover. In love with open source and design.
More about me