Anton Forsberg
Anton Forsberg

Reputation: 66

Importing CSS-url from SASS with Webpack

I'm working with web components, (specifically lit-element), and I want to share a common stylesheet across several different components. What I am trying to achieve is to get the url of the compiled CSS file when I import it in my JS-component so that I can add it as an external stylesheet in the markup.

component.js

import styleUrl from 'url-loader!../styles/placeholder.scss';
...
render(){
    return html`
        <link rel="stylesheet" href="${styleUrl}">
        ...
    `

}

So I want the styleUrl to be the url to the compiled css.

Currently my webpack config looks something like the following Webpack config

...
{
    test: /\.scss$/,
    use: [
        "style-loader",
        "css-loader", 
        "sass-loader"
    ]
}

Upvotes: 0

Views: 1713

Answers (1)

Umbo
Umbo

Reputation: 3142

The problem is that you're not extracting the stylesheets from the bundle: the compiled sass is being added to the bundle, therefore is not available as separate files each one with its own url.

To do so you can use tools such as extract-loader:

import stylesheetUrl from "file-loader!extract-loader!css-loader!main.css";
// stylesheetUrl will now be the hashed url to the final stylesheet

However LitElement has better styling options such as the static styles property that takes advantage of the new Constructable Stylesheets API, not to mention that the documentation partially discourages the use of <link>.

There is a webpack plugin that automatically prepares the compiled sass for being adopted by LitElement: lit-scss-loader.

import style1 from './style-1.scss';
import style2 from './style-2.css';

class LitSassLoaderTest extends LitElement {

    // TypeScript
    static styles = [
        style1,
        style2,
    ];

    // JavaScript
    static get styles() {
        return [
            style1,
            style2,
        ];
    }
}

Upvotes: 4

Related Questions