RadValentin / postcss-prefix-selector

Prefix all CSS rules with a selector
MIT License
165 stars 16 forks source link

Does not prefix styles in *.css files imported via @import #102

Closed mellis481 closed 2 years ago

mellis481 commented 2 years ago

I have the following rule defined in my webpack.config:

module: {
  rules: [
    {
      test: /\.(sa|sc|c)ss$/,
      use: [
        'style-loader',
        'css-loader',
        {
          loader: 'postcss-loader',
          options: {
            postcssOptions: {
              plugins: [
                [
                  'postcss-prefix-selector',
                  {
                    prefix: '.___my-app',
                  },
                ],
              ],
            },
          },
        },
        'sass-loader',
      ];
    }
  ]
};

It has been working great, but I just discovered a scenario where it will not scope styles. Let's say I have a React component and I have import './custom.scss'; at the top of the file. custom.scss looks like this:

@import 'styles.css';
@import 'styles.scss';

Styles in styles.scss WILL be scoped, but styles in styles.css will NOT be scoped. The problem has to do with the use of @import with *.css files because if I use import './styles.css'; directly in my React component, styles WILL be scoped.

RadValentin commented 2 years ago

@mellis481 I think the issue is that when you write @import 'styles.css' in a SASS file, this gets treated as a plain CSS import and isn't passed through the webpack loaders. What happens if you omit the .css extension from the file name? (like it says here)

Also, I see that the SASS docs mention that @import is being phased out in favour of @use, see this and this.

mellis481 commented 2 years ago

@RadValentin Thanks for your response!

Omitting the .css extension from @import statement results in the styles correctly being scoped.

Replacing @import with @use also results in styles correctly being scoped, even when the the @use statement includes the .css extension.

I think I'll add an eslint rule to my project to error on @import statement.

Thanks again!