javascript - 如何将 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',
}),
]
};
解决方案
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
推荐阅读
- jquery - 替换 jquery 中的类,停止元素执行所需的操作
- python-3.6 - 如何解决 python 3.6.5 中的错误“ImportError: cannot import name 'HIDE_CURSOR'”
- laravel - 迁移 - 写入或更新时重复键 - 仅适用于测试环境
- java - 是否有替代方法:Drive.getDriveClient(), Drive.getDriveResourceClient, ... 来自已弃用的 api?
- loops - 如何在 Xamarin.forms 中创建循环后台服务
- python - 我正在尝试使用堆栈反转在 python 中的文本文件中写入的一些内容
- javascript - 重新启动我的绘图功能不起作用
- c++ - 如何将共享库链接到另一个共享库
- javascript - 如何更新数据库中的所有行并在不刷新的情况下显示更新的数据?
- react-native - 如何修复 react-native 中的“无法读取未定义的属性‘导航器’”错误