Solution 1 :

I’ve found the solution – use css (scss) modules.

1. I modified my webpack config:

{
  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. I added declares to 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. And now I can use css classes like modules

//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;
}

Solution 2 :

One approach, although not without a bit of work, would be to replace your classnames with unique strings to avoid the potential for overwrites.

Problem :

I am creating a plugin for the browser, and on some websites my classes are being overridden by the website’s classes.

Is it impossible to add class name prefix for all classes (in HTML and in SCSS files) with webpack? I use webpack: “4.42.0”

Or maybe I need to use another approach?

By