How to import css in node_modules to svelte

Total
0
Shares

To import css in node_modules to Svelte, you will need rollup-plugin or Svelte-preprocess.

Using rollup-plugin

Follow these steps –

Step1: Install rollup css plugin

npm install -D rollup-plugin-css-only

Step2: Open rollup.config.js

Now we need to edit rollup.config.js file.

First, import rollup-plugin-css-only at the top of the file and then go to plugins array and add a combined css path –

import css from "rollup-plugin-css-only";
....
....
plugins: [
    css({ output: "public/build/combined.css" }),
    svelte({
.....
.....

With this change, Svelte will combine all the external css in node_modules folder, and put it in public/build folder with name combined.css.

Step3: Put combined css file in index.html

Since we got the combined.css file in previous step, now we need to add it to the index.html file so that our website can use it.

<link rel="stylesheet" href="/build/combined.css" />

Step4: Use css files in node_modules to Svelte

Suppose you want to add bootstrap.css in App.svelte, then you can use this –

<script>
    import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

Using svelte-preprocess

Svelte introduced proprocess so that you can write your own preprocessor. It will help in using TypeScript, SCSS, PostCSS etc. You can learn more about it from official documentation and library page.

Follow these steps to import css from node_modules using svelte-preprocess –

Step1: Open rollup.config.js file

In rollup.config.js file, import svelte-preprocess and include path of node_modules css –

import autoPreprocess from 'svelte-preprocess';

...
svelte({
    preprocess: autoPreprocess({
        postcss: true,
        scss: { includePaths: ['src', 'node_modules'] },
    })
}),
...

Step2: Use css files in components

Now you can use css files in your components. For example, we can import bootstrap.css in App.svelte like this –

<style lang="scss" global>
    @import '../node_modules/bootstrap/dist/css/bootstrap.min';
    @import '../node_modules/bootstrap/scss/bootstrap.scss';
</style>

Note: Use lang="scss" and global in <style> tag. Also, do not include .css extension in the @import statement.

    Tweet this to help others