You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Preact构建时如何保留模板HTML文件中的style标签?

Preact 3.0 保留模板index.html内style标签的解决方案

Preact 3.0默认的构建逻辑会识别所有样式内容并提取到单独的CSS文件,你可以通过以下两种方式实现需求:


方法1:调整构建配置(长期稳定方案)

如果你使用官方preact-cli脚手架

  1. 在项目根目录新建preact.config.js文件
  2. 添加如下配置,直接排除标记好的style标签被提取处理:
export default (config, env, helpers) => {
  // 调整HTML压缩规则,保留指定style标签
  const htmlPlugin = helpers.getPluginsByName(config, 'HtmlWebpackPlugin')[0];
  if (htmlPlugin) {
    htmlPlugin.plugin.options.minify = {
      ...htmlPlugin.plugin.options.minify,
      ignoreCustomFragments: [/<style id="keep-this-tag"[\s\S]*?<\/style>/]
    };
  }

  // 禁止CSS loader提取index.html内的样式内容
  const cssRules = helpers.getLoadersByName(config, 'css-loader');
  cssRules.forEach(item => {
    item.rule.exclude = item.rule.exclude || [];
    item.rule.exclude.push(/index\.html$/);
  });
};

如果你使用Vite自定义搭建项目

修改vite.config.js添加如下配置:

import { defineConfig } from 'vite';
import preact from '@preact/preset-vite';

export default defineConfig({
  plugins: [preact()],
  html: {
    minify: {
      ignoreCustomFragments: [/<style id="keep-this-tag"[\s\S]*?<\/style>/]
    }
  }
});

方法2:临时快速方案

无需修改配置,直接给需要保留的style标签加特殊注释标记,绝大多数CSS提取工具会自动忽略这类样式,不会打包到独立CSS文件里:

<style id="keep-this-tag">
  /*! no-extract */
  some-styles-that-should-not-be-put-in-style.css-file
</style>

内容的提问来源于stack exchange,提问作者Peng Xiao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:36:00