【问题标题】:How to add class name prefix for all classes (in html and in scss files) with webpack?如何使用 webpack 为所有类(在 html 和 scss 文件中)添加类名前缀?
【发布时间】:2020-05-24 16:22:19
【问题描述】:

我正在为浏览器创建一个插件,在某些网站上,我的类被网站的类覆盖。

是否无法使用 webpack 为所有类(在 HTML 和 SCSS 文件中)添加类名前缀?我使用 webpack:“4.42.0”

或者也许我需要使用其他方法?

【问题讨论】:

    标签: html css webpack


    【解决方案1】:

    我找到了解决方案 - 使用 css (scss) 模块。

    1.我修改了我的 webpack 配置:

    {
      test: cssRegex,
      exclude: cssModuleRegex,
      use: getStyleLoaders({
        importLoaders: 1,
        sourceMap: isEnvProduction && shouldUseSourceMap,
        modules: {
          getLocalIdent: getCSSModuleLocalIdent,
        },
      }),
      sideEffects: true,
    },
    {
      test: cssModuleRegex,
      use: getStyleLoaders({
        importLoaders: 1,
        sourceMap: isEnvProduction && shouldUseSourceMap,
        modules: {
          getLocalIdent: getCSSModuleLocalIdent,
        },
      }),
    },
    {
      test: sassRegex,
      exclude: sassModuleRegex,
      use: getStyleLoaders({
          importLoaders: 3,
          sourceMap: isEnvProduction && shouldUseSourceMap,
          modules: {
            getLocalIdent: getCSSModuleLocalIdent,
          },
        },
        'sass-loader'
      ),
      sideEffects: true,
    },
    {
      test: sassModuleRegex,
      use: getStyleLoaders({
          importLoaders: 3,
          sourceMap: isEnvProduction && shouldUseSourceMap,
          modules: {
            getLocalIdent: getCSSModuleLocalIdent,
          },
        },
        'sass-loader'
      ),
    },

    2。我向 react-app-env.d.ts 添加了声明:

    declare module '*.css' {
      const classes: { readonly [key: string]: string };
      export default classes;
    }
    
    declare module '*.scss' {
      const content: {[className: string]: string};
      export default content;
    }

    3.现在我可以使用像模块这样的 css 类了

    //Header.tsx
    
    import React from "react";
    import styles from './Header.scss';
    
    export default class Header extends React.Component {
        render() {
            return (
                <header className={styles.header}>
                    Hello World!
                </header>
            )
        }
    }
    //Header.scss
    
    .header {
      color: $white;
      background-color: $green;
      padding: 8px 10px;
      font-weight: 500;
      font-size: 16px;
    }

    【讨论】:

      【解决方案2】:

      一种方法是用唯一的字符串替换您的类名,以避免被覆盖的可能性,尽管并非没有一些工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-02-04
        • 1970-01-01
        • 2023-01-27
        • 2010-09-29
        • 2022-10-18
        • 2011-05-20
        • 1970-01-01
        相关资源
        最近更新 更多