【问题标题】:How to @import CSS file in Angular?如何在Angular中@import CSS文件?
【发布时间】:2019-12-19 12:22:32
【问题描述】:

我有一个文件需要在另一个 css 文件中使用。

为此,我已将此添加到 angular.json 文件中:

   "styles": ["src/assets/css/theme.scss"],

然后我尝试在css文件中使用它:

@import "theme.scss";

Angular 找不到此路径。

【问题讨论】:

  • 导入文件时需要引用正确的路径。如果 theme.scss 与 css 文件位于同一文件夹中,则您可以使用 @Import './theme.scss'; 否则(例如,如果是上一级):@import '../theme.scss';

标签: angular angular6 angular8


【解决方案1】:

如果您想指向组件中的 css/scss 文件,您可以在 options 节点中的 angular.json 中添加样式文件夹的快捷方式,如下所示:

        "my-app": {
            "root": "...",
            "sourceRoot": "...src",
            "projectType": "application",
            "architect": {

                "build": {
                    [...]
                    "options": {
                        [...]
                        "stylePreprocessorOptions": {
                          "includePaths": [
                            "projects/my-app/src/styles" // path to your styles folder
                          ]
                        }
                    }
                    
                },

            }
        },

那么,每当你使用@import "...";,它都会从css文件夹开始,所以你可以使用@import "theme.scss";

【讨论】:

  • +1 这是一个很好的答案,但它没有指出 theme.scss 的源代码将在构建过程中移动到 /dist 文件夹,然后人们可以下载来自网络服务器的源代码。源代码从未使用过,因为 SASS 已将其导入到 JavaScript 包中。因此,请使用上述选项,但将您的代码从资产文件夹中移开。该文件夹用于存放静态文件。
  • 我收到错误,不允许stylePreprocessorOptions
  • @OPV,它应该与“选项”在同一级别添加。我会修正我的答案
【解决方案2】:

转到angular.json 并包含"styles": ["../assets/css/theme.scss","styles.css"],

【讨论】:

    猜你喜欢
    • 2017-08-01
    • 2012-03-25
    • 2015-02-27
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 2019-10-07
    相关资源
    最近更新 更多