LoginSignup
0
0

Webアプリケーションにコンテキストパスを設定した時のparcelの設定

Last updated at Posted at 2023-08-16

前提

parcelでCSS, JavaScriptをbundleしているSpringBootのWebアプリケーション
CSSではurl()の構文で画像を呼び出している

style.scss
.hoge {
  background-image: url(../img/icon.png);
}

こちらをparcelでbundleすると、SCSSからCSSに変換される

bundle.css
.hoge {
  background-image: url(/icon.869a98d2.png);
}
  • build時にbundle.cssと同じディレクトリに画像が配置されるため、絶対パス指定になっている
  • キャッシュのためにファイル名にハッシュが追加されている (公式)

困りごと

SpringBootのpropertyファイルで、アプリケーションにコンテキストパスを追加した

application.properties
server.servlet.context-path=/foo

この変更により、エンドポイントが以下のように変わる

CSS等の静的ファイルの配置場所も同様

一方、上述の通り、bundle後のCSSは画像をルートから絶対パスで指定している

bundle.css
.hoge {
  background-image: url(/icon.869a98d2.png);
}

そのため、CSSから画像を呼び出す際にコンテキストパスが加味されず
/fooなしの http://localhost:8080/icon.869a98d2.png を見に行ってしまう
しかしコンテキストパス追加によって画像の配置URLは変わっているため、404となる

対応

parcelの起動コマンドに--public-urlオプションを追加した

parcel build assets/js/index.js --out-dir target/classes/static --out-file bundle.js

parcel build assets/js/index.js --out-dir target/classes/static --out-file bundle.js --public-url ./

これにより、bundle後のCSSで画像を呼び出す際、ルートからの絶対パス指定がされなくなる

bundle.css
.hoge {
  background-image: url(icon.869a98d2.png);
}

foo配下にcssと画像が配置されている状態であるため、
bundle.cssからurl(/icon.869a98d2.png)と指定しても取得できないが、
相対パス指定でurl(icon.869a98d2.png)とすれば問題なく取得ができる

foo
 |--- bundle.css
 |--- icon.869a98d2.png

なおpublic-url /fooとすれば以下のようになるため、絶対パス指定を防ぐ設定というわけではない
こちらでも動くが、propertyファイルで行っているコンテキストパスの設定と同期を取る必要があり、二重管理のリスクが発生する
またテスト環境ではコンテキストパスを変えたい等の場合も面倒ごとが増える
そのため相対パスでの指定が吉と思われる

bundle.css
.hoge {
  background-image: url(/foo/icon.869a98d2.png);
}

参考

Set the public URL to serve on (parcel公式)
https://en.parceljs.org/cli.html#set-the-public-url-to-serve-on

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