I'm using css-modules with AngularJS 1.5 components now. The stack is webpack
+ css-loader?modules=true
+ angular 1.5 components
+ pug
.
Currently I have to do the following steps to use css modules in my pug template.
// my-component.js
import template from 'my-component.pug';
import styles from 'my-component.css';
class MyComponent {
constructor($element) {
$element.addClass('myComponent'); // ------ (1)
this.styles = styles; // ------ (2)
}
}
angular.module(name, deps)
.component('my-component', {
controller: MyComponent,
template: template,
});
// my-component.pug
div(class={{ ::$ctrl.styles.fooBar }}) FooBar // ----- (3)
// my-component.css
.myComponent { background: green; }
.fooBar { color: red; }
There are two problems:
Every component has to inject
$element
and set its class name manually. The reason for doing this is, AngularJS component tag itself exists in the result HTML without any classes, which makes CSS difficult. For example, if I useMyComponent
above like this:<div> <my-component></my-component> </div>
it will generate the following HTML:
<div> <my-component> <div class="my-component__fooBar__3B2xz">FooBar</div> </my-component> </div>
Compared to ReactJS,
<my-component>
in above result HTML is an extra, sometimes it makes CSS difficult to write. So my solution is (1), to add a class to it.The class in template is too long (3). I know it is the correct way to reference
$ctrl.styles.fooBar
but this is way too long.
My ideal solution would be like this:
// my-component.js
angular.module(name, deps)
.component('my-component', {
controller: MyComponent,
template: template,
styles: styles,
});
// my-component.css
div(css-class="fooBar") FooBar
The idea is to:
- make
angular.module().component
support an extrastyles
attribute, which will automatically do (2)this.styles = styles;
in the controller, and apply (1)$element.addClass()
as well. - directive
css-class
to apply$ctrl.styles
to element.
My question is, I have no idea how to implement idea 1 above (2 is easy). I appreciate if anyone could share some light on this.
I came up with a solution which I don't quite satisfy with.
Angular component can accept a function as template and inject with
$element
. docTherefore we could attach the main class for component (
.myComponent
) in the template function, then regex replace all the occurance of class names with compiled class names.There are still one place to be improved that
decorateTemplate
uses regex replacement and template has to use a special notation${className}
to specify the css-modules class names.Any suggestions are welcome.
UPDATE
I updated my
decorateTemplate()
function to leverage pug features, so that local class names can be written as._localClassName
.Although this is much easier it does not eliminate the quirky notation (begin with
_
for local class names) and regex replace.Any suggestions are welcome.