0
0

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 1 year has passed since last update.

npm run watch時の無限ループ

Posted at

概要

laravel mixを使用しており

$npm run watch

実行時に無限ループに入りビルドが実行できなかった。
結構ハマってしまい、あまり情報が出ていなかったので記録に残しておきます。

動作環境(動作環境には関係なさそうではあるが一応)
laravel:^9.0
laravel-mix:^4.1.4

ドキュメント

laravel 8.xアセットコンパイルMix
のURL処理が今回のお話です

結論

webpack.mix.js

const mix = require('laravel-mix');

mix
    .sass('resources/sass/app.scss', 'public/css/app.css')
    .js('resources/js/app.js', 'public/js/app.js')
    .options({
        processCssUrls: false //このオプションを追加する
    });

詳細

デフォルトではprocessCssUrlsこのオプションはtrueに設定されている。

webpack.mix.js
.options({
    processCssUrls: true
});

この時の挙動は

app.scss
.example {
    background: url('../images/user/example.png');
}

resouces/images/user配下のexample.pngを見つけ
public/images下にコピーします。

そしてビルド後のcssは

app.css
.example {
    background: url(/images/example.png?d41d8cd98f00b204e9800998ecf8427e);
}

このような形になります。

しかし、プロジェクトによっては
画像をresoucesフォルダではなくpublicフォルダにそのまま入れているプロジェクトもあるかと思います。

私は後者の方でした。

となるとprocessCssUrls: trueがどういう挙動をとるかよくわかりません。
なぜならコピーする画像がresoucesディレクトリにないのですから。

でもlaravelMixは賢くてpublicからのpathも見に行って見つけてらpublic/images下にコピーします。

public/images/user/example.pngに画像があり
その状態でビルドを走らせると
public/images/example.pngが生成されます。

無限ループの原因

以上のような挙動をとることがわかりましたが
では

app.scss
.example {
    background: url('../images/example2.png');
}

これをビルドするとどうなるでしょうか?

画像はpublic/images/example2.pngにあります。

これをビルドすると
public/images/example2.pngを
コピーして
public/images/example2.pngを生成します。

変更が加わったと判定され
再度ビルドが走ります。

.
.
.
無限ループ

これが無限ループの原因でした。

resouces/images配下に画像を置く運用の場合はtrueに設定すればいいと思うのですが

webpack.mix.js
.options({
    processCssUrls: true
});

public/images配下に画像を置く運用の場合は
falseにしておいた方が綺麗かなと思います。

webpack.mix.js
.options({
    processCssUrls: false
});

そしてscssのpathの指定の仕方は

app.scss
.example {
    background: url('/images/user/example.png');
}

絶対パスで指定した方がいいかなと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?