首页 > 解决方案 > 如何将 css 样式从文件注入到 WebComponent

问题描述

我想知道是否可以.css将从文件导入的样式注入 WebComponent(如果是,请告诉我如何实现这一点)。我使用 Webpack在文件style-loader中加载.css样式,.js但是我不知道如何(或者是否可能)将这些样式注入到 WebComponent 模板中。

我知道我可以从.js模板字符串中声明的文件中导出样式,但这不是我正在寻找的解决方案。

我创建了一个带有简单示例的存储库,您可以在此处找到该示例:inject-css-from-file。我还在这里包括这些文件:

索引.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);

索引.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',
        }),
    ]
};

标签: javascriptcsswebpackweb-component

解决方案


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


推荐阅读