LoginSignup
1
3

More than 3 years have passed since last update.

parcel buildのビルド結果をgithub pagesで公開すると、jsファイルの読み込みが404で失敗する。

Last updated at Posted at 2020-07-29

事象

index.htmlmain.jsword.jsの3つのファイルから構成されるフロントエンドアプリケーションがあるとします。

index.html
<!DOCTYPE html>
<body>
  <div id="title"></div>
  <div id="description"></div>
  <script src="main.js"></script>
</body>
main.js
import Word from './word.js'

document.getElementById("title").innerHTML = Word.title
document.getElementById("description").innerHTML = Word.description
word.js
export default {
  title: "Hello World",
  description: "Parcelのテストです"
}

parcel build index.htmlによりこのアプリケーションをビルドします (parcel-bundler v1.12.4)

$ parcel build index.html
⠹ Building index.html...
✨  Built in 36.94s.

dist/main.a0e33e9b.js        1.57 KB     1.08s
dist/main.a0e33e9b.js.map      735 B      17ms
dist/index.html                123 B    35.01s
Done in 60.34s.

ビルド結果であるdistディレクトリ配下をGitHubのparcel-sampleレポジトリのmasterブランチにプッシュ。parcel-sampleレポジトリをgithub pagesとして公開する設定をした後、所定のURL(https://nekotheshadow.github.io/parcel-sample)にアクセスしたところ、index.htmlは想定通り表示されるものの、jsファイルの読み込みがステータスコード404によって失敗する事象が発生しました。

image.png

原因と対策

公開URLを明示せずにビルドしたため、あらぬjsファイルを読み込もうとしたために起きた現象です。つまりparcel buildの際に公開URLを指定する--public-urlオプションを利用することにより問題は解決します (参考: https://parceljs.org/cli.html)

具体的には以下のように指定してビルドを実施します

$ parcel build index.html --public-url https://nekotheshadow.github.io/parcel-sample/
✨  Built in 30.23s.

dist/main.a0e33e9b.js        1.61 KB     1.19s
dist/main.a0e33e9b.js.map      735 B       6ms
dist/index.html                168 B    28.32s
Done in 50.77s

dist配下のビルド結果を改めてparcel-sampleにプッシュし、https://nekotheshadow.github.io/parcel-sampleにアクセスすると、想定通り動作することが確認できました。

image.png

Chromeの開発者ツールでも、jsファイルの読み込みが正しくできていることがわかります。

image.png

参考

1
3
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
1
3