SCSS and “:host([active])”

2019-05-19 20:44发布

问题:

I need such construction in scss:

:host {
    background: #fff;

    &([active]) {
        background: #000;
    }
}

meaning output like:

:host {
    background: #fff;
}
:host([active]) {
    background: #000;
}

But I can't get it working any way I've tried. Is there any way to escape parentheses I don't know or something not overcomplicated?

Just inserting piece of raw css like `code` in CoffeeScript would be great, but I do not see anything like this in documentation.

回答1:

If you want to use this shadow DOM selectors in the scss files you cant use :host(<selector>) nested right now. A workaround is to repeat :host for each selector you want to use.

SCSS:

:host {
    background: #fff;
}
:host([active]) {
    background: #000;
}

CSS (the same):

:host {
  background: #fff;
}

:host([active]) {
  background: #000;
}

You could try it here: http://sassmeister.com/



回答2:

Unfortunatly sass still doesn't support this. I made an additional workaround to support nested state selectors on :host

Assuming you also use gulp-sass to compile your sass to css you can do the following:

npm install gulp-replace

Next add the following to the top of the gulp script that compiles your sass:

var replace = require('gulp-replace');

And add the following to your sass compile pipe:

.pipe(replace(':host:hover', ':host(:hover)'))

Now you can use the following construct in your sass:

Sass

:host {
    &:hover {
        color: red;
    }
}

The replace function will change your css to look like this:

CSS

:host(:hover) {
  color: red;
}

Your gulp script should look something like this:

Gulp

var gulp = require('gulp');
var replace = require('gulp-replace');
var sass = require('gulp-sass');

gulp.task('sass', function () {
    return gulp.src('./src/sass/**/*.scss')
        .pipe(sass({
            outputStyle: 'expanded',
            precision: 10,
        }))
        .pipe(replace(':host:hover', ':host(:hover)'))
        .pipe(gulp.dest('./dist/css'));
});

You can add more states by expanding the replace part of your gulp script.