0
1

More than 3 years have passed since last update.

Vue.js+Webpackで作ったプロジェクトをGitHub Pagesのサブディレクトリでの公開時PublicPath設定について

Last updated at Posted at 2020-03-11

はじめに

Vue.js+Webpackで作ったプロジェクトをそのままBuildして、GitHub Pagesへサブディレクトリとしてデプロイしました。
- 開発環境(Local) ⇒https://localhost:8080/
- 本番環境(GitHub Pages) ⇒https://<username>.github.io/<repository>/
GitHub PagesのURLにアクセスしたところ、imgタグの画像とCSSに定義した画像パスが404エラーとなって、5時間もはまってしまったので、解決するまでのメモを残しておきたいと思います。

GitHub Pagesに公開するために設定すべきところ

1.コンフィグファイルのパス

config/vue.config.js
  module.exports = {
  build: {
    index: path.resolve(__dirname, '../docs/index.html'),
    assetsRoot: path.resolve(__dirname, '../docs'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/<repository>/',
    productionSourceMap: true,
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    bundleAnalyzerReport: process.env.npm_config_report
  }

index
GitHub Pagesは「docs」配下のindex.htmlを探しに行くので、デフォルトの「dist」を「docs」に修正する。

assetsRoot
ビルドファイルの出力先をデフォルトの「dist」から「docs」に修正する。

assetsPublicPath(ハマり箇所1)
デフォルト値 ⇒ assetsPublicPath: '/'
設定すべき値 ⇒ assetsPublicPath: '/<repository>/'
   
デフォルト値のままの場合、ドメイン直下(https://<username>.github.io/)に assets がある体のコードが出力されてしまい、画像ファイルなどを読み込めないためリポジトリ名を設定する。

2.Vueルータ

src/router.js
  export default new Router({
  mode: 'history',
  base: '/<repository>/',
  routes: [
    {
      path: '/',
      name: 'Top',
      component: Top
    },
    {
      path: '/about',
      name: 'About',
      component: About
    },
    {
      path: '*',
      name: 'Not Found',
      component: PageNotFound,
      title: 'Not Found'
    }
  ]
})

baseオプション
baseオプションのを追加する。追加しないと画面遷移がおかしくなるため。(ハマり箇所2)

3.そのほか

「window.location.host」を使用したところがあれば注意してください。Local開発環境の動きと違うため(「.github.io」まで取得)。

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