头图

Create a new Angular project using the Angular CLI:

ng new my-sassy-app --style=scss

Create the following scss file:

styles.scss is the main scss file we use, which imports _variables.scss and _mixins.scss starting with an underscore:

 // src/sass/styles.scss

@import './variables';
@import './mixins';

Finally, specify this styles.scss file in angular.json:

 "styles": [
  "sass/styles.scss"
],

Now that we have our new _variables.scss and _mixins.scss files, we want to use them in our other Angular Components. In other projects, you may be used to accessing Sass variables defined in these scss files from anywhere.

In Angular CLI, all components are self-contained, as are their Sass files. In order to use variables defined in _variables.scss in a component's Sass file, you need to import the _variables.scss file.

One way is to use the component's 相对路径 @import, such as ../../ this way of writing. If you have a lot of nested folders or end up needing to move these scss files, this might not be a good idea - it's poorly readable and prone to errors.

A good way to do this is to use the alias alias syntax, represented by the special tilde: ~ . In English, the word for ---af1c4fb70026bc1f65d0d99a34960b9c is tilde .

 // src/app/app.component.scss

@import '~sass/variables';

// now we can use those variables!

The tilde (~) will tell Sass to look in the src/ folder, which is a shortcut for importing Sass files ( short cut ).

Some tips for importing files in the node_modules folder in an Angular project

We explain it through a practical example. Suppose we introduce a dependency `bootstrap-sass:

npm install bootstrap-sass --save

This npm package has some scss files:

We can update angular.json to introduce the node_modules folder:

 {
    ...
    "apps": [{
        "root": "src",
        ...
        "stylePreprocessorOptions": {
            "includePaths": [
              ".",
              "./stylings",
              "../node_modules/bootstrap-sass/assets/stylesheets"
            ]
        }
        
    }]
}

Then, in the style file of the Component, you can use 相对路径 to import the scss files in the node_modules folder:

 // hello.component.scss
@import "variables";
@import "stylings2/variables"; 
@impoer "bootstrap/variables";

h1 {
    color: $brand-color;
    font-size: $font-size-large;
    font-family: $font-family-serif;
}

注销
1k 声望1.6k 粉丝

invalid