San*_*mas 7 iframe reactjs webpack webpack-style-loader
我正在尝试在iframe中渲染我的React组件。我通过使用库“ react-frame-component”来使其工作。问题在于样式是在“ head”元素末尾的iframe外部加载的。我想更改它以将其加载到“ iframe”元素的“ head”中。我正在使用Webpack生成包含JS和CSS的捆绑软件,并且看到可以通过设置选项“ insertInto”来更改“ style-loader”加载样式的位置,但这会引发错误:
Uncaught Error: Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.
Run Code Online (Sandbox Code Playgroud)
这是我的React组件:
import Frame from 'react-frame-component'
...
ReactDOM.render(
<Frame id="someId">
<Provider store={Store.get()}>
<Container/>
</Provider>,
</Frame>,
document.body
);
Run Code Online (Sandbox Code Playgroud)
这是我在Webpack配置中的“样式加载器”:
{
loader: 'css-loader',
options: {
insertInto: () => document.querySelector("#someId"),
},
}
Run Code Online (Sandbox Code Playgroud)
我认为问题在于,当webpack尝试包含样式时,该组件未呈现。如何解决呢?
您需要将样式作为占位符加载到临时元素中,然后使用 Javascript 将这些样式克隆到新框架中。
// index.html
...
<div id="dynamic-styles"></div>
...
Run Code Online (Sandbox Code Playgroud)
// webpack.config.js
...
{
loader: 'css-loader',
options: {
insertInto: () => document.getElementById("dynamic-styles"),
},
}
...
Run Code Online (Sandbox Code Playgroud)
// some.js
...
const stylesContainer = document.getElementById('dynamic-styles');
const frame = document.getElementById('someID');
const frameHead = frame.contentWindow.document.head;
[...stylesContainer.children].forEach(styleNode => {
const newStyle = document.createElement('style');
newStyle.textContent = styleNode.textContent;
frameHead.appendChild(newStyle);
});
Run Code Online (Sandbox Code Playgroud)
我还没有测试过上面的代码片段,但我知道这个概念是有效的。我觉得它已经说明了要点。
可能有更好的方法来做到这一点,但我还没有进行足够的研究来弄清楚。如果能够让 webpack 制作单独的样式包,这样每个配置的框架都可以自动延迟加载它自己专用的捆绑 css,那就太好了
| 归档时间: |
|
| 查看次数: |
1018 次 |
| 最近记录: |