首页 > 解决方案 > 如何以优化的方式将样式文件导入 Angular +2 项目?

问题描述

我在 Angular 6 项目中使用 Angular Material 主题,我有 3 个样式文件:

1)styles.scss(主样式文件,它定义在Angular.json文件中)

@import "styles/themes/blue-light.scss";
// Basics
* {
    margin: 0;
    padding: 0;
}
...

2)blue-light.scss(带有角度材质定义颜色的样式)

@import '~@angular/material/theming';
@import '../custom-theme.scss';
@include mat-core();
$my-app-primary: mat-palette($mat-blue, 900);
$my-app-accent: mat-palette($mat-light-blue, 500, 900, A100);
$my-app-warn: mat-palette($mat-deep-orange);
$my-app-theme: mat-light-theme($my-app-primary, $my-app-accent, $my-app-warn);
@include angular-material-theme($my-app-theme);
@include custom-theme($my-app-theme);

3)custom-theme.scss(当我在我的自定义组件中使用调色板的主要颜色时的文件)

// Import library functions for theme creation.
@import '~@angular/material/theming';

@mixin custom-theme($theme) {

    // Extract the palettes you need from the theme definition.
    $primary: map-get($theme, primary);
    $accent: map-get($theme, accent);

    .mat-nav-list .active {
        background: mat-color($primary, 50);
        color: mat-color($primary);
    }
}

目前代码可以工作,但我希望以优化的方式开发,我在下面的Material 文章中读到,自定义主题文件不应该导入其他 SCSS 文件。这将在您的 CSS 输出中复制样式。如果你想在其他 SCSS 文件中使用你的主题定义对象(例如,在我的例子中是 $custom-theme),那么主题对象的定义应该被分解成它自己的文件,与包含 mat-core 和角度材料主题混合。

我无法理解这意味着什么以及它应该如何实现,我需要一个创建自定义主题以及如何有效地导入样式文件的指南

标签: angularcssangular-materialmaterial-designscss-mixins

解决方案


一般来说,导入未压缩的样式文件很好,因为 webpack(或您使用的任何捆绑器)会自动为您缩小和丑化所有样式文件。

关于自定义材质,请参考角材质文档的这一部分:https ://material.angular.io/guide/theming#defining-a-custom-theme

那里说你只需要一个,因为 SCSS 文件来自定义具有此内容的材料

@import '~@angular/material/theming';
// Plus imports for other components in your app.

// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat-core();

// Define the palettes for your theme using the Material Design palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue. Available color palettes: https://material.io/design/color/
$candy-app-primary: mat-palette($mat-indigo);
$candy-app-accent:  mat-palette($mat-pink, A200, A100, A400);

// The warn palette is optional (defaults to red).
$candy-app-warn:    mat-palette($mat-red);

// Create the theme object (a Sass map containing all of the palettes).
$candy-app-theme: mat-light-theme($candy-app-primary, $candy-app-accent, $candy-app-warn);

// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include angular-material-theme($candy-app-theme);

推荐阅读