Krzysztof Kaczyński
Krzysztof Kaczyński

Reputation: 5071

How to inject css styles from file to WebComponent

I am wondering is it possible to inject .css styles imported from file to WebComponent (If yes then please tell me how can I achieve this). I used Webpack style-loader to load .css styles inside .js a file but then I do not know how (or is it possible) to inject those styles into WebComponent the template.

I know that I can export styles from .js file declared in template string but it is not a solution which I am looking for.

I created a repository with simple example which you can find here: inject-css-from-file. I also include those files here:

index.html :

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
    <kk-app></kk-app>
</body>
</html>

index.js :

import style from "./index.css";

const template = `
<style>${style}</style>
<div>
    <p>Example component</p>
</div>
`;

export class App extends HTMLElement {
    constructor() {
        super()
        this.attachShadow({ mode: 'open' });
        this.shadowRoot.innerHTML = template;
    }
}
customElements.define('kk-app', App);

index.css :

p {
    color: red;
}

webpack.config.js :

const HTMLWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
    mode: 'production',
    entry: './index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader'],
            },
        ],
    },
    resolve: {
        extensions: ['.js'],
    },
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
    },
    plugins: [
        new HTMLWebpackPlugin({
            template: path.resolve(__dirname, 'index.html'),
            filename: 'index.html',
        }),
    ]
};

Upvotes: 2

Views: 1402

Answers (1)

Krzysztof Kaczyński
Krzysztof Kaczyński

Reputation: 5071

So the solution for that was to remove style-loader from webpack.config.js. Rule for .css file should look like that:

rules: [
    {
        test: /\.css$/,
        use: ['css-loader'],
    },
],

I do not know why but style-loader changed this .css styles into an object.

P.S. If you are using MiniCssExtractPlugin.loader it will cause same problem

Upvotes: 1

Related Questions