[英]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).我想知道是否可以将从文件导入的
.css
样式注入到 WebComponent (如果是,那么请告诉我如何实现这一点)。 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.我使用 Webpack
style-loader
在.js
文件中加载.css
样式,但是我不知道如何(或是否可能)将这些样式注入到 WebComponent 模板中。
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.我知道我可以从模板字符串中声明的
.js
文件中导出样式,但这不是我正在寻找的解决方案。
I created a repository with simple example which you can find here: inject-css-from-file .我创建了一个带有简单示例的存储库,您可以在此处找到: inject-css-from-file 。 I also include those files here:
我还在此处包含了这些文件:
index.html :索引.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 :索引.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 :索引.css :
p {
color: red;
}
webpack.config.js : 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',
}),
]
};
So the solution for that was to remove style-loader
from webpack.config.js
.所以解决方案是从
webpack.config.js
删除style-loader
。 Rule for .css
file should look like that: .css
文件的规则应如下所示:
rules: [
{
test: /\.css$/,
use: ['css-loader'],
},
],
I do not know why but style-loader
changed this .css
styles into an object.我不知道为什么但
style-loader
将此.css
样式更改为一个对象。
PS If you are using
MiniCssExtractPlugin.loader
it will cause same problemPS如果你使用
MiniCssExtractPlugin.loader
它会导致同样的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.