0

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"
    ]
}

1 Answers1

4

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,
        ];
    }
}
Umbo
  • 3,042
  • 18
  • 23
  • 1
    Thanks for a great reply! Just to clarify: The reason I wanted the URL is because of the duplication of CSS that occurs when several elements share the same stylesheet. In this case it's some placeholder styles that I would rather not have to declare for every element that uses them. – Anton Forsberg Feb 19 '19 at 21:04
  • I see, had the same problem in some projects. The styles property/webpack loader it's pretty handy in this kind of situation, especially if you want to use scss :) – Umbo Feb 20 '19 at 15:17