我有 vite 配置和 React 应用程序。
import react from '@vitejs/plugin-react';
import * as path from 'path';
import { defineConfig, splitVendorChunkPlugin } from 'vite';
import htmlPlugin from 'vite-plugin-html-config';
import { dependencies } from './package.json';
const exclVendors = ['react', 'react-router-dom', 'react-dom'];
function renderChunks(deps: Record<string, string>) {
let chunks = {};
Object.keys(deps).forEach((key) => {
if (exclVendors.includes(key)) return;
chunks[key] = [key];
});
return chunks;
}
// https://vitejs.dev/config/
export default defineConfig({
server: {
port: 8082
},
envPrefix: 'APP_',
resolve: {
alias: [{ find: '@', replacement: path.resolve(__dirname, 'src') }],
},
plugins: [
react(),
htmlPlugin({ favicon: './src/assets/logo.svg' }),
splitVendorChunkPlugin(),
],
build: {
sourcemap: false,
rollupOptions: {
output: {
manualChunks: {
...renderChunks(dependencies),
},
},
},
},
});
我想在 Shadow Dom 中创建应用程序。
应用程序构建在shadow Dom中,但css添加到头部。
如何将所有CSS添加到shadow Dom?
我尝试安装 vite-plugin-css-injected-by-js 插件,但它没有从 head css 中移动 css
在 esbuild 中,这是通过 esbuild-css-modules-plugin 完成的,但我还没有找到如何在 vite 中执行相同的操作。
我不确定您是否已经有了解决方案,但我可以分享一个现在在 Shadow dom 中对我有用的解决方案。
首先,使用
?inline
选项在以下 CSS 文件中生成样式导出。
import styles from "./App.css?inline"
function App() {
// ... other code
return (
<>
<style>{styles}</style>
<div className="chrome-extension-boilerplate">
{/* ...other components*/}
</div>
</>
)
}
或者,您可以直接在 Shadow dom 元素中添加样式。它看起来很相似,但您必须将样式直接注入到 Shadow Doom 根中。
function attachStyleToShadowDom(shadowWrapper: ShadowRoot, cssContent: string) {
// create variable to attach the tailwind stylesheet
const style = document.createElement("style")
// attach the stylesheet as text
style.textContent = cssContent
// apply the style
shadowWrapper.appendChild(style)
}
export function createShadowRoot(root: Element, styles: string) {
// Set shadow root inside of root element
const shadowRoot = root.attachShadow({ mode: "open" })
root.appendChild(shadowRoot)
// Add React App root node and styles
const rootIntoShadow = document.createElement("div")
rootIntoShadow.id = appRootId
shadowRoot.appendChild(rootIntoShadow)
attachStyleToShadowDom(shadowRoot, styles)
return rootIntoShadow
}
这里是我正在构建的 Chrome 扩展样板的链接:https://github.com/EduardoAC/browser-extension-boilerplate。一旦我知道得更好了。我也来分享这个