1

我现在正在玩 Angular2。我是网络和所有 javascript 世界的初学者,因为我主要是后端 .Net 开发人员。我对我们作为 javascript 库的所有选择感到困惑,这些库似乎以不同的方式做几乎相同的事情,但有一些明显的差异。

就我而言,我想知道当您可以使用组件的 styleUrls 属性时,ng2 组件中的 CSS 加载器的目的是什么。

我正在关注本教程http://teropa.info/blog/2016/02/28/metabubbles-generation-art-with-angular-2.html#extracting-a-circles-service但我正在尝试重现它使用打字稿代替。

在“使用 CSS 设置组件样式”部分,他们使用 Webpack 的 CSS 加载器,如下所示

@Component({
  selector: 'mb-canvas',
  template: `...`,
  styles: [require('css!./canvas.component.css').toString()],
  directives: [CircleComponent]
})

目前,据我所知,这似乎没用,因为我们可以像这样使用组件的 styleUrls 属性

@Component({
  selector: 'mb-canvas',
  template: `...`,
  styleUrls: ['./canvas.component.css'],
  directives: [CircleComponent]
})

谁能帮我理解?如果使用 CSS 加载器是一个好习惯,因为我使用的是 SystemJS,我认为不支持加载 CSS 文件,我应该切换到 webpack 还是我找到的任何多个加载器。装载机确实人满为患,因为每次我查看示例时,我都会找到另一个装载机;)

4

1 回答 1

0

I think you mixed some things here:

  1. css-loader is a Webpack feature, for loading css files using 'require' syntax. If you use Webpack, it is nice to use this in order to load you external css files using 'require'. You can even change the css into a string and add it to 'styles' array.

  2. styleUrls is Angular 2 feature (it is a property of Angular's Component decorator. As you can see here ), It will be written to the head of the document.

So, it seems that the results are similar, used in a different way with different tools.

EDIT

So, the advantages of using 'require' with webpack are:

  • You don't have to pack each style file
  • You don't have to deploy all style files
  • You don't have to do an extra http request for each style file
  • You don't have to do hacks to make the url point to the cdn and not web page source
于 2016-03-06T20:45:28.930 回答