preboot / angular-webpack

A complete, yet simple, starter for Angular v2+ using webpack
MIT License
1.29k stars 556 forks source link

Best practice to work with SASS and mixins/variables #186

Open samfrach opened 8 years ago

samfrach commented 8 years ago

Hello,

my angular2 project is starting to look great, but I have a problem structuring my SCSS files.

I have one external scss file for each of my angular components and I would like them to import a kind of "utils.scss" and "variables.scss" where all my mixins/variables, etc. would be located.

in src/app/XX.....XX/component.scss, I can add a @import '../../../../style/app.scss'; and it would work... but it's painful to add it in each file + a relative path is not convenient to type...

What could be the solution ??

Solution #1 : with aliases in sass-loader I could add an "@import 'scss-root';" in all my component.scss files. From the sass-loader documentation, I can add an alias " 'scss-root$': root('src/style/app.scss')" It resolves fine for an "import 'scss-root';" in a component.ts file but not in a component.scss file (error is File to import not found or unreadable: scss-root). By the way, what is the objectif to add a scss file in the typescript file ? is it for inline styles ?

Solution #2: using the "sass-resources-loader" This loader allows to add imports to all .scss file. This could be exactly what I want but there is a bug (https://github.com/shakacode/sass-resources-loader/issues/12). I hope it will be fixed. I've added it with npm install sass-resources-loader --save-dev then in webpack.config.js ({test: /.scss$/, exclude: root('src', 'style'), loader: 'raw!postcss!sass!sass-resources'}, + config.sassResources = ['app/sass/variables.scss', 'app/sass/mixins/*.scss'];)

Solution #3: any suggestion ?

thank you for your help and ideas.

samfrach commented 8 years ago

I have all my ng2 components splitted into a .ts, a .html and a .scss file.

In order to use mixins and constants in any of my scss files, I don't want to add in all of them an "@import '../.././../utils' " (note the relative path which is boring to type..) Since the sass-resources-loader is able to act as if I had included this @import line, I'm happy to use it. I've had difficulties to find the correct syntax on how to use it. Now it is working.

Finally, in the webpack.config.js file, I have :

added : config.sassResources = ['./src/app/style/utils.scss']; AND changed this line : {test: /.scss$/, exclude: root('src', 'style'), loader: 'raw!postcss!sass!sass-resources'},

and of course an npm install sass-resources-loader --save-dev

The loader can't handle the @import directive itself, so I you have to import more than one file, put each of them in the config.sassResources array....

@Foxandxss - wouldn't be a good idea to integrate sass-resources-loader in the webpack-starter ? The effort is tiny and the efficience is great ...