サーバを無料で使いたいマンなので全てGitHub Pagesでなんとかしようとするマンです。よろしくお願いします。
GitHub PagesでSPAしようとすると、index.html以外にアクセスされた場合にGitHub Pagesで用意された404が表示されてしまうのでなんとかしようとした時の記録です。
SPAモードにする
nuxt.config.js
module.exports = {
mode: 'spa' // これを追記
}
index.html以外にアクセスされた際にNuxt.js(index.html)にリダイレクト
static/404.html
<script>
sessionStorage.redirect = location.href;
</script>
<meta http-equiv="refresh" content="0;URL='/'"/>
static/js/404-redirect-ghpages.js
;(function() {
const redirect = sessionStorage.redirect
delete sessionStorage.redirect
if (redirect && redirect !== location.href) {
history.replaceState(null, null, redirect)
}
})()
nuxt.config.js
module.exports = {
head: {
script: [{ src: '/js/404-redirect-ghpages.js' }] // これを追記
},
}
デプロイ
$ yarn add --dev push-dir
package.json
"scripts": {
"build": "nuxt build",
"deploy": "push-dir --dir=dist --branch=gh-pages --cleanup"
}
$ yarn build
$ yarn deploy
参考
https://dev.to/_evansalter/github-pages-and-single-page-apps