为什么我的代码会复制文件的 css?

Why does my code duplicate the css of a file?

在 Sass 中,我有一些组件(导航栏、页脚)和一些 @mixins(字体)和一个控制字体的函数。

@import字体的位置,在字体的函数里做@include,在这个函数里我只选择我要用的字体。

问题是,当我将组件(导航栏和页脚)分隔为 "partials" 时,它们具有相同的来源,我在每个 .scss 的这些来源中给出了 @import .

然后它会在我生成的 .scss 文件中生成重复代码。我想知道这有什么好的做法,如果我做得对,以及如何避免 .scss?

中的这些重复项

我不确定这是否回答了你的问题——但为了防止在 Sass 中出现重复,我会创建一个 mixin 来检查是否已经创建了 @include

SCSS

//  Global list to keep track of what mixins has been included 
$include-once: (); 

//  Mixin helper to be used inside other mixins we would like 
//  not to produce duplicate content
@mixin once($mixin-name) {
   //  check if mixin name exists in our list 
   @if not index($include-once, $mixin-name) {

       //  add mixin name to list (using the global flag)
       $include-once: append($include-once, $mixin-name) !global;

       //  print out the content of the mixin
       @content;
   } 
}



//  Use example
@mixin font {
    //  wrap content in the include once wrapper passing the name of the mixin 
    @include once(font){

        //  make sure font import is not nested 
        @at-root {
            @import url("https://fonts.googleapis.com/css?family=Open+Sans");
        }
    }
}


//  Test
.foo { @include font; color: red; }
.bar { @include font; color: green; }
.baz { @include font; color: blue; }


CSS输出

@import url("https://fonts.googleapis.com/css?family=Open+Sans")
.foo {
  color: red;
}
.bar {
  color: green;
}

.baz {
  color: blue;
}



因为我看不到你的代码,所以我不确定你是如何导入你的资源的。但是,如果您只生成一个 .css 文件,一个好的做法是导入将要编译的文件中的所有内容,而不是每个部分。

假设您具有以下结构:

styles
├─ components
│   ├─ _footer.scss
│   └─ _navbar.scss
├─ settings
│   ├─ _functions.scss
│   └─ _mixins.scss
└─ styles.scss

在此示例中,styles.sccs 是唯一将被编译的,它将仅用于导入所有部分(顺序很重要):

// Settings

@import './settings/mixins';
@import './settings/functions';

// Components

@import './components/footer';
@import './components/navbar';

然后您可以在您的组件中使用任何 mixin 或函数,所有内容都只导入一次。

我玩游戏有点晚了,但我遇到了这个问题,使用部分或使用 @include 不起作用。对我有用的是使用 css-nano-webpack-plugin https://www.npmjs.com/package/cssnano-webpack-plugin. I'm using webpack v5, so could not get it to work using the webpack mini-css-extract-plugin https://www.npmjs.com/package/mini-css-extract-plugin.

请记住,下面的代码片段最小化了 css PER scss 文件。因此,文件之间的重复可能仍会出现在 .css 输出文件中。

所以,像这样将它包含在你的 webpack 配置中(来源是 npmjs cssnano-webpack-plugin 站点)

const CssnanoPlugin = require('cssnano-webpack-plugin');
 
module.exports = {
  module: {
    loaders: [
      {
        test: /.s?css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'sass-loader'
        ]
      }
    ]
  },
  optimization: {
    minimizer: [
      new CssnanoPlugin()
    ]
  }
};
´´´