在ViteJs项目的生产中保留css链接的id

问题描述 投票:0回答:1

在 Vanilla Typescript Vite 项目中,我需要制作一个单页应用程序。我需要使用两个 css 文件。所以在html入口页面中,我使用2个链接样式表文件。我需要在应用程序中禁用一个并激活另一个。

我看到我可以使用该房产

disabled

HTMLLinkElement。

所以我在 html 页面上的链接中添加了一个 id,如下所示:

<link rel="stylesheet" href="./styles/login.css" id="css_login">
<link rel="stylesheet" href="./styles/lobby.css" id="css_lobby">

但在生产中,ViteJs 会在没有 id 的情况下对其进行转换:

<link rel="stylesheet" href="/assets/lobby.d0dbc25d.css">
<link rel="stylesheet" href="/assets/login.32f19747.css">

我无法选择 JS 中的链接来禁用或激活特定文件。

有人可以帮助我吗?我昨晚花了很多时间试图解决这个问题,但什么也没找到。无论我做什么,链接标签属性都会消失。

谢谢

css build vite
1个回答
0
投票

禁用属性效果很好,但通过在构建后修改index.html以及初始加载时组合样式的闪烁,它很快就会变得很糟糕。

所以我找到了 Vite + React 的可行替代方案。我使用 Shadow DOM 渲染多个根,并通过 jsx 本身中的链接元素加载样式表。这种方式使用起来要简单得多,因为影子 DOM 会被动地限定冲突的样式表。我想这对于 vanilla TS 是可行的。

在 Shadow DOM 中渲染 React root 示例:

import { createRoot } from "react-dom/client";

// create root container where react element will be inserted
let container = document.createElement("div");
container.classList.add("react-container");

// attach shadow DOM to container
const shadowRoot = container.attachShadow({ mode: "open" });

// create react element
const reactButton = <button>Submit</button>;

// get hold of an existing element in HTML DOM
const domElement = document.getElementById("name");

// insert root container element in HTML DOM after the existing element
domElement.after(container);

// shadow DOM as react root
const root = createRoot(shadowRoot);

// render react element inside shadow DOM
root.render(reactButton);

使用链接元素在影子 DOM (Vanilla JS) 中注入样式示例:

...
this.shadowRoot.innerHTML = `
  <link rel="stylesheet" href="/button.css" />
  <style>
    /* your component specific styles go here */
  </style>
  ...
`;
...

有关在 Shadow DOM 中渲染 React 根的更多信息:https://gourav.io/blog/render-react

有关 Shadow DOM 中样式的更多信息:https://lamplightdev.com/blog/2021/03/23/how-to-share-styles-in-the-shadow-dom/

© www.soinside.com 2019 - 2024. All rights reserved.