2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ng test を実行した時にscssファイルのimportでエラーになる問題の解決方法

Last updated at Posted at 2018-12-25

Angular を利用したプロジェクトで、ng test コマンドで Karma + Jasmine でユニットテストを行った際にハマったことの備忘録です。
本記事では、Angular のテストツールは Karma + Jasmineを想定しています。

問題

ng testを実行して、下記のようなエラーが出た場合を想定します。

ERROR in ./src/app/app.component.scss
Module build failed (from ./node_modules/sass-loader/lib/loader.js):

@import 'theme';
^
      File to import not found or unreadable: theme.
      in /Users/xxxx/project/src/app/app.component.scss (line 1, column 1)
 @ ./src/app/app.component.ts 16:21-52
 @ ./src/app/app.component.spec.ts
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts

該当の scss ファイルは例として、下記のようなものを想定します。

src/app/app.component.scss
@import 'theme';

h1 {
  color: $main;
}

インポート先のテーマ用 scss ファイルは下記とします。

src/theme/default/theme.scss
$main: red;

app.component.scss の@import 'theme';のようにルート相対パスで記述するために、 angular.json のarchitect.build.optionsstylePreprocessorOptions.includePathsに任意のパスを追加しています。 

angular.json
"architect": {
  "build": {
    "builder": "@angular-devkit/build-angular:browser",
    "options": {
      "stylePreprocessorOptions": {
        "includePaths": [
          "src/theme/default"
        ]
      },
...

解決方法

architect.build.optionsと同様にarchitect.test.optionsstylePreprocessorOptions.includePathsを設定します。

angular.json
"test": {
  "builder": "@angular-devkit/build-angular:karma",
  "options": {
    "stylePreprocessorOptions": {
      "includePaths": 
        "src/theme/default"
      ]
    },
...

上記の記述を追加すると、ng testを実行すると、 Karma が動作するようになります。

参考

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?