Anidetrix / rollup-plugin-styles

🎨 Universal Rollup plugin for styles: PostCSS, Sass, Less, Stylus and more.
https://anidetrix.github.io/rollup-plugin-styles
MIT License
242 stars 43 forks source link

SCSS exports support #165

Open dangnelson opened 3 years ago

dangnelson commented 3 years ago

I'm looking for a way to use SCSS exports in my project.

Currently this works in React like so:

//Colors.scss
$black: #000000;

:export {
  black: $black;
}
//Component.js
import Colors from '../Colors.scss'

console.log(Colors.black)

But I can't seem to get this to work with rollup. Is this something this plugin already supports?

teetotum commented 3 years ago

The feature you are referring to is Interoperable CSS (ICSS). The popular css-loader for webpack-based projects supports it. Your React project presumably uses webpack as bundler and therefore it worked for you. As far as I can tell rollup-plugin-styles does currently not support Interoperable CSS. This is one of the reasons I still use webpack for my projects.

pmrotule commented 3 years ago

As mentioned on stackoverflow, I'm willing to contribute a PR to add that feature since we really need it. Looking at css-loader source code, it uses icss-utils which means it shouldn't be so much effort to add it to rollup-plugin-styles.

The current behavior of css-loader is to inject the styles if there is any ruleset defined and export the hashed name of each class together with the exported variables inside :export {}.

Considering the following breakpoints.scss

$breakpoint-mobile: 360px;
$breakpoint-tablet: 768px;
$breakpoint-desktop: 1200px;

.myClass {
  color: green;
}

:export {
  mobile: $breakpoint-mobile;
  tablet: $breakpoint-tablet;
  desktop: $breakpoint-desktop;
}

and js file:

import breakpoints from './breakpoints.scss'

breakpoints will be equal to:

{
  mobile: '360px',
  tablet: '768px',
  desktop: '1200px',
  myClass: 'myClass_3Tq_8',
}

This behavior makes total sense in my opinion and that's what I would go for if you guys agree. No need for extra plugin options. It would be a breaking change in a way since the current behavior of rollup-plugin-styles is to export the minified CSS as a string. I would guess nobody uses it, but I might be wrong.

Any objection, comment?

pmrotule commented 3 years ago

Well, I just tested styles({ modules: true }) and I'm getting the exact behavior I was looking for and the one from css-loader I just described 🙈.

This was breakpoints.scss compiled with rollup-plugin-styles and the option modules: true:

import n from '../../node_modules/rollup-plugin-styles/dist/runtime/inject-css.js';

var css = "";
var modules_6f076289 = {"mobile":"360px","tablet":"768px","desktop":"1200px"};
n(css,{});

export default modules_6f076289;
export { css };
//# sourceMappingURL=breakpoints.scss.js.map

This issue could be closed.