LoginSignup
3
5

More than 5 years have passed since last update.

Applying 3rd party CSS in angular-cli

Posted at

angular-cli を使って作ったプロジェクト(SystemJS は使わない)で 3rd party CSS (node_modules/*/ 以下)を当てようとしてつまずいたので備忘録。

サンプルは

angular-cli で作ったプロジェクトで ag-grid-ng2-example のような Grid を 表示したい。ただ、CSS がうまく当たらないために意図した表示にならない・・・。

何が問題だった?

index.html のコメントにもある通り、CSS をどうロードするか自体は ag-Grid 自体の問題ではない。例では 特に build せず index.html で直接ロードしているが、ng serve を実行したときには webpack が build して bundle を作るため、この部分を index.html にコピーしただけでは意図した通りの表示にならない:

index.html
    <!-- ag-grid CSS -->
    <!-- In your build, you will probably want to include the css in your bundle. -->
    <!-- To do this you will use a CSS Loader. How to do this is not an ag-Grid -->
    <!-- problem, so I've not included how to do it here. For simplicity, and -->
    <!-- explicitness, the CSS files are loaded in directly here. -->
    <link href="node_modules/ag-grid/dist/styles/ag-grid.css" rel="stylesheet" />
    <link href="node_modules/ag-grid/dist/styles/theme-fresh.css" rel="stylesheet" />

解決策

いつもありがとう stackoverflow 。2つの解決策が提示されていた。

Option 1

  • angular-cli.json 内の styles array で直接指定する
angular-cli.json
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      //...(snip)...
      "styles": [
        "styles.css",
          "../node_modules/ag-grid/dist/styles/ag-grid.css",
          "../node_modules/ag-grid/dist/styles/theme-fresh.css"
      ],

Option 2

  • src/styles.css で該当の CSS を import する
    • angular-cli で作成した default の angular-cli.json を使って、styles.css を参照していると仮定する。
    • この方法の場合、 Option 1 で直接指定した angular-cli.json 内のエントリーは削除しておく必要がある。
angular-cli.json
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      //...(snip)...
      "styles": [
        "styles.css"
      ],
src/styles.css
/* You can add global styles to this file, and also import other style files */
@import "../node_modules/ag-grid/dist/styles/ag-grid.css";
@import "../node_modules/ag-grid/dist/styles/theme-fresh.css";

まとめ

どちらの方法でも期待通りに Grid が表示できた。「どちらがよい」という記述はないが、「angular-cli で全部やる」という強い意志なら Option 1、直感的なのは Option 2 、なんだろうか。

とはいえ、Option 2 も angular-cli.json の styles array で styles.css が指定されているから効いているので、まわりくどいが以下のような Option 1 & 2 のハイブリッド版でもよいのかもしれない。

  • angular-cli.json 内で styles.css 以外の CSS ファイル(たとえばvendor.css)を指定
  • vendor.css 内で 3rd party vendor の CSS を import

いずれにせよ angular-cli.json を書き換えた場合は ng serve の再起動(angular-cli.json の再読み込み)が必要なので忘れないようにしたい。

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5