LoginSignup
16
17

More than 5 years have passed since last update.

vue-routerのgithub-pages用設定

Posted at

webpackでgithub pagesをdeployする際のハマりどころ の続き。

SPAをgithub-pagesにdeployした場合、
サーバ上のroot dirがhttps://USER_NAME.github.io/となっているので
本番環境のSPA内でのroot dirをhttps://USER_NAME.github.io/GITHUB_PROJECT_NAMEになるように変更しなければならない。
そうしないとSPA内でのページ遷移時にGITHUB_PROJECT_NAME dirを無視した遷移となり404になってしまう。

code

src/router/router.jsが

import VueRouter from 'vue-router'
import Vue from 'vue'
import Index from 'src/pages/Index'
import About from 'src/pages/About'

Vue.use(VueRouter)

const routes = [{
  path: '/',
  name: 'index',
  component: Index
}, {
  path: '/about',
  name: 'about',
  component: About
}]

const scrollBehavior = (to, from, savedPosition) => {
  if (savedPosition) {
    // savedPosition is only available for popstate navigations.
    return savedPosition
  } else {
    const position = {}
    // new navigation.
    // scroll to anchor by returning the selector
    if (to.hash) {
      position.selector = to.hash
    } else {
      position.x = 0
      position.y = 0
    }
    return position
  }
}
var router = new VueRouter({
  mode: 'history',
  scrollBehavior,
  routes,
  linkActiveClass: 'active'
})

export default router

となっているとしたら

config/dev.env.js

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  ROOT_BASE: '""' // new!
})

config/prod.env.js

module.exports = {
  NODE_ENV: '"production"',
  ROOT_BASE: '"GITHUB_PROJECT_NAME/"' // new!
}

src/router/router.js

var router = new VueRouter({
  mode: 'history',
  base: process.env.ROOT_BASE, // new!
  scrollBehavior,
  routes,
  linkActiveClass: 'active'
})

を追加する。
この設定でhttps://USER_NAME.github.io/GITHUB_PROJECT_NAMEからの遷移で、GITHUB_PROJECT_NAME dirが無視されるは問題は解決。

それから

しかし、
https://USER_NAME.github.io/GITHUB_PROJECT_NAME/aboutページへ直接アクセスすると404ページになる。
SPAなのでabout.htmlの実態は用意していない。そのためサーバ側の設定が必要になる。

GitHub Pages and Single-Page Apps

ここにあるように404ページにリダイレクトを仕込むかなんやかんやする必要がありそう。
もうnuxtで作った方がいいんじゃないのか感があるが、後日対応する。

16
17
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
16
17