use mdc sass files in angular-cli projects - css

I have a project using angular-cli. I am using mdc components/. I want to import individual component's sass files. For this,
1) I have changed the default styleExt using this command
ng set defaults.styleExt scss
2) Renamed the file style.css to style.scss.
3) In angular-cli.json changed
"styles": [
"styles.css"
],
to
"styles": [
"styles.scss"
],
4) Added stylePreprocessorOptions configuration to include path
"stylePreprocessorOptions": {
"includePaths": [
"node_modules"
]
}
5) Finally in style.scss file imported
#import '~#material/button/mdc-button';
but this is showing
ERROR in ./~/css-loader?{"sourceMap":false,"importLoaders":1}!./~/postcss-loader?{"ident":"postcss"}!./~/sass-loader/lib/loader.js?{"sourceMap":false,"precis
ion":8,"includePaths":["D://SK//Study//Material//MaterialWithAngularDemo//src//node_modules"]}!./src/styles.scss
Module build failed:
undefined
^
File to import not found or unreadable: #material/theme/mixins.
Parent style sheet: D:/SK/Study/Material/MaterialWithAngularDemo/node_modules/#material/button/mdc-button.scss
in D:\SK\Study\Material\MaterialWithAngularDemo\node_modules\#material\button\mdc-button.scss (line 17, column 1)
# ./src/styles.scss 4:14-187
# multi ./src/styles.scss
Am I missing something?

There was a mistake in includePath instead of node_modules it should be ../node_modules.
"stylePreprocessorOptions": {
"includePaths": [
"../node_modules"
]
}
After changing this, it is working fine.

Related

Why is my VS Code live sass compiler settings not compiling my scss file?

I have a lot of scss partials so I changed the settings to this: ```{
"es6-css-minify.cssPostfix": "",
"liveSassCompile.settings.autoprefix": [
],
"liveSassCompile.settings.formats": [
{
"format": "compressed",
"extensionName": ".css",
"savePath": "/wp-content/themes/dawn-child",
}
],
"liveSassCompile.settings.includeItems": [ "/wp-content/themes/dawn-child/style.scss" ],
}
but this is not compiling scss files in the mentioned folder. I even tried to change the saved path to dawn-child and dawn-child/style.css but neither seemed to work.
I'm using the glenn marks live sass compiler. Is there anything wrong with my settings?
Try putting a period in front of the directories:
"savePath": "./wp-content/themes/dawn-child",
And:
"liveSassCompile.settings.includeItems": [ "./wp-content/themes/dawn-child/style.scss" ],
The period indicates the current directory of the .json file you're running.

Add SCSS support to Vue project

In my packages.json file by default I get:
"postcss": {
"plugins": {
"autoprefixer": {}
}}
When I add <style lang='scss'> It doesn't compile like magic like it does for Typescript support. I know I will need to specify some NPM package as devDependencies and specify something above in the postcss section to get scss to compile, but I can't find any documentation outside of webpack so I am lost.
See https://vue-loader.vuejs.org/guide/pre-processors.html.
For example, to compile our <style> tag with SASS/SCSS:
npm install -D sass-loader node-sass
In your webpack config:
module.exports = {
module: {
rules: [
// ... other rules omitted
// this will apply to both plain `.scss` files
// AND `<style lang="scss">` blocks in `.vue` files
{
test: /\.scss$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
]
}
]
},
// plugin omitted
}
Now in addition to being able to import 'style.scss', we can use SCSS
in Vue components as well:
<style lang="scss"> /* write SCSS here */ </style>
Any content inside the block will be processed by webpack as if it's
inside a *.scss file.

How to add global style to angular 6/7 library

I was trying to add global styles in the same way like in angular app, but it totally does not work.
My libraries' name is example-lib, so I added styles.css to /projects/example-lib/. I added styles in main angular.json file:
...
"example-lib": {
"root": "projects/example-lib",
"sourceRoot": "projects/example-lib/src",
"projectType": "library",
"prefix": "ngx",
"architect": {
"build": {
"builder": "#angular-devkit/build-ng-packagr:build",
"options": {
"tsConfig": "projects/example-lib/tsconfig.lib.json",
"project": "projects/example-lib/ng-package.json",
"styles": [
"projects/example-lib/styles.css" <!-- HERE
],
},
...
But when I tried build library using command:
ng build example-lib
I got error:
Schema validation failed with the following errors:
Data path "" should NOT have additional properties(styles)
I guess that is the other way to add global styles in separate library. Anyone can help me?
I have a workaround for this. Just create the root component of your library without view encapsulation and all its styles will be then global.
my-library.component.ts
import { Component, OnInit, ViewEncapsulation } from '#angular/core';
#Component({
selector: 'lib-my-library',
templateUrl: './my-library.component.html',
styleUrls: ['./my-library.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class MyLibraryComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
my-library.component.html
<!-- html content -->
my-library.component.scss
#import './styles/core.scss';
Now your my-library.component.scss and core.scss are global
styles/core.scss
body {
background: #333;
}
core.scss is optional, I just like to keep the root files clean.
Update: In case you want your mixins and variables too, then follow this answer.
As #codeepic already pointed out, there is currently a standard solution.
In ng-package.json add
"assets": ["./styles/**/*.css"]
The provided paths should be the paths to your files. At the same time, they will be the paths inside your /dist folder.
On build, the files will be copied to /dist. Users of your library will be able to add them to their global styles as follows.
/* styles.css */
#import url('node_modules/<your-library-name>/styles/<file-name>');
This way you can copy any type of files.
P.S. When used with CSS, do not forget that you can create an index.css file that can be imported just like node_modules/<your-library-name>/styles.
From Compiling css in new Angular 6 libraries:
install some devDependencies in our library in order to bundle the css:
ng-packagr
scss-bundle
ts-node
Create css-bundle.ts:
import { relative } from 'path';
import { Bundler } from 'scss-bundle';
import { writeFile } from 'fs-extra';
/** Bundles all SCSS files into a single file */
async function bundleScss() {
const { found, bundledContent, imports } = await new Bundler()
.Bundle('./src/_theme.scss', ['./src/**/*.scss']);
if (imports) {
const cwd = process.cwd();
const filesNotFound = imports
.filter(x => !x.found)
.map(x => relative(cwd, x.filePath));
if (filesNotFound.length) {
console.error(`SCSS imports failed \n\n${filesNotFound.join('\n - ')}\n`);
throw new Error('One or more SCSS imports failed');
}
}
if (found) {
await writeFile('./dist/_theme.scss', bundledContent);
}
}
bundleScss();
Add _theme.scss inside the /src directory of the library that actually contains and imports all the css that we want to bundle.
Add postbuild npm script to run the css-bundle.ts
Include it in the styles tag in your Application in the angular.json
From this issue solution
Install cpx and scss-bundle as Dev dependencies to your package.json. Then add the following entries in your package.json "scripts" property:
"scripts": {
...
"build-mylib": "ng build mylib && npm run build-mylib-styles && npm run cp-mylib-assets",
"build-mylib-styles": "cpx \"./projects/mylib/src/lib/style/**/*\" \"./dist/mylib/style\" && scss-bundle -e ./projects/mylib/src/lib/style/_style.scss -d ./dist/mylib/style/_styles.scss",
"cp-mylib-assets": "cpx \"./src/assets/**/*\" \"./dist/mylib/assets\"",
...
}
Replace "mylib" with your real library name and then just run in your terminal build-mylib. That would compile your scss assets to your dist folder.
You use this global styles in your actual Angular project just import them in your angular.json file within your project settings:
"styles": [
"src/styles.scss",
"dist/my-shiny-library/_theme.scss"
],
(use dist if your project is in the same workspace, or node_moduled if its an imported library)
1- be sure you are putting your styles inside the library
example:
projects/your-lib-name/assets/styles.css
2- then in your ng-package.json (in the lib for sure) put the assets rule
{
"$schema": ... ,
"dest": ... ,
> "assets": [
> "./assets/*"
> ],
"lib": ...
}
3-
in your application, you can use this asset
"styles": [
"../your-lib-name/assets/styles.css"
]
this is a tutorial

Weird css path anomaly in component, if css file not in the same directory

If I put the css file into the same directory as my component is, everything works, but when I edit the path to another directory I get this error in browser console:
Uncaught Error: Expected 'styles' to be an array of strings."
Works:
styleUrls: [
'admin.css'
],
Doesn't work:
styleUrls: [
'../../css/admin.css'
],
Works with scss file which is in the same directory:
styleUrls: [
'../../css/admin.scss'
],
Any ideas?
Found a solution. I had project default styles set to scss. To fix do following:
Open angular.json file
Change .scss
"schematics": {
"#schematics/angular:component": {
"styleext": "scss"
}
}
to .css
"schematics": {
"#schematics/angular:component": {
"styleext": "css"
}
}
and restart with ng serve

Using scss as default style sheet in Angular 6+ (styleExt)

Apparently the way to declare the default stylesheet extension changed from Angular 6 onwards. The styleExt property in the angular.json is not recognised any longer.
For new projects this can be set with an option on the CLI --style=scss on the new command.
However, how do you change this for exsting projects that I migrate from Angular <5 or if you forgot to do this during project creation?
This question is meant to be strictly related to the breaking changes by the version 5 to 6 of Angular.
The position on which this is set changed in the angular.json. There are 2 ways to set this option now.
Via the Angular CLI:
ng config schematics.#schematics/angular:component.styleext scss
Directly in the angular.json:
"schematics": {
"#schematics/angular:component": {
"styleext": "scss"
}
}
Angular 9 Update:
Note that from Angular 9 onwards styleext is renamed to style. So we end up with:
ng config schematics.#schematics/angular:component.style scss
and
"schematics": {
"#schematics/angular:component": {
"style": "scss"
}
}
To go from css to scss for an existing project, follow these steps:
In angular.json file
In build part and in test part, replace:
"styles": ["src/styles.css"], by "styles": ["src/styles.scss"],
Replace:
"schematics": {}, by "schematics": { "#schematics/angular:component": { "style": "scss" } },
Using ng config schematics.#schematics/angular:component.styleext
scss command works but it does not place the configuration in the
same place.
In your project rename your .css files to .scss

Resources