IT이야기

github/gitlab 페이지가 있는 vuejs 기록 모드

cyworld 2022. 4. 21. 21:25
반응형

github/gitlab 페이지가 있는 vuejs 기록 모드

누가 Vue.js를 어떻게 일하게 할 수 있는지 알아냈나?history modeGitHub 또는 GitLab 페이지와 함께 사용하시겠습니까?

와 잘 통한다.hash mode, 그러나 나는 사용하고 싶지 않다.hash modeSEO 관련 이유로.

라우터 모드에 대한 참조: https://router.vuejs.org/en/essentials/history-mode.html

는 이 에서 나에게 맞는 해결책을 찾았다.

해결책을 요약하기 위해, 나는 다음과 같은 것들을 만들었다.404.html파일을 작성하여 프로젝트의 루트 폴더에 추가하십시오.

<!DOCTYPE html>
<html>
    <head>
        <script>
            // ====================================================================================================================
            // This text is simply to make sure the 404.html file is bigger than 512 bytes, else, internet explorer will ignore it.
            // Thank you internet explorer for requiring such awesome workarounds in order to work properly
            // ====================================================================================================================
            sessionStorage.redirect = location.href;
        </script>
        <meta http-equiv="refresh" content="0;URL='/'">
    </head>
</html>

그리고 나서 나는 이 자바스크립트를 더했다.index.html:

(function(){
    var redirect = sessionStorage.redirect;
    delete sessionStorage.redirect;
    if (redirect && redirect != location.href) {
        history.replaceState(null, null, redirect);
    }
})();

GitLab Pages는 확실하지 않지만 GitHub Pages에서는 index.html 파일 대신 404.html 파일을 통해 전체 Vue.js 애플리케이션을 제공할 수 있다.배포 시 index.html 파일의 이름을 404.html 파일로 바꾸기만 하면 된다.

같은 문제에 부딪쳐 이 질문을 발견하고 위에서 두 가지 해결책을 모두 시도해 보았지만 운이 없었다.그런 다음 다음과 같이 결합해 보십시오.

여기 내 것404.html파일

<!DOCTYPE html>
<html>
<head>
    <title>My App</title>
    <script>
        // ========================================
        // Credits:
        // - https://stackoverflow.com/a/50259501
        // - https://stackoverflow.com/a/50247140
        // ========================================
        const segment = 1

        sessionStorage.redirect = '/' + location.pathname.slice(1).split('/').slice(segment).join('/')

        location.replace(
            location.pathname.split('/').slice(0, 1 + segment).join('/')
        )
    </script>
</head>
</html>

그리고 여기 내 것이 있다.main.js파일

const app = new Vue({
    router,
    store,
    render: h => h(App),
    created () {
        if (sessionStorage.redirect) {
            const redirect = sessionStorage.redirect
            delete sessionStorage.redirect
            this.$router.push(redirect)
        }
    }
})

app.$mount('#app')

그리고 그것은 동작한다.

A가 필요할 수도 있다.404.htmlhttps://github.com/rafrex/spa-github-pages/blob/gh-pages/404.html을 해킹하다.

또는 정적 html https://nuxtjs.org/guide#static-generated-pre-rendering-으로 vue를 미리 렌더링해 보십시오.

파티에 조금 늦었지만 나는 이것을 할 방법이 있다.나는 Vue CLI 3과 GitHub 페이지를 사용하고 있다.

우선 모든 원본 파일을 원본 분기에 커밋하고dist다음 셸 명령을 사용하여 마스터 분기에 폴더(Vue에서 생성):

# deploy.sh

#!/usr/bin/env sh

# abort on errors
set -e


# build
echo Building. this may take a minute...
npm run build

# navigate into the build output directory
cd dist
# create a copy of index.html
cp index.html 404.html
find . -name ".DS_Store" -delete

# if you are deploying to a custom domain
echo 'custom.com' > CNAME

# remove git and reinitialise
rm -rf .git
echo Deploying..
git init
git add -A
git commit -m 'deploy'

# deploy
git remote add origin https://github.com/User/repo.github.io
git push origin master --force

cd -
rm -rf dist

GitHub 페이지는 경로를 찾을 수 없을 때404.html. 내가 작성한 배포 프로그램은 index.html의 사본을 만들고 이름을 404.html로 짓는다.그래서 효과가 있는 겁니다.

편집: 이것은 404개의 응답을 반환하고 구글은 그것을 인덱싱하지 않을 것이기 때문에 SEO 목적에 좋지 않을 것이라는 것을 깨달았다.

페리의 솔루션으로 볼 때, 나는 Vue 인스턴스를 만들 때 리디렉션을 처리하는 대신 항법 가드가 더 잘 작동할 수 있을 것이라고 생각한다.

나는 기본적으로 beforeEnter 가드를 인덱스 경로에 추가해서 인덱스 페이지를 건너뛰고 대상 페이지로 바로 이동하도록 했다.

const routes = [
{
  path: '/',
  component: Index,
  beforeEnter: (to, from, next) => {
    if (sessionStorage.getItem('redirect') !== null) {
      const redirect = sessionStorage.redirect
      delete sessionStorage.redirect
      next(redirect)
    } else {
      next()
    }
  }
},
]

이게 도움이 되길 바래.

2021년 답안

GitLab을 사용하는 사용자를 위해 이제 a를 사용하여 index.html로 리디렉션할 수 있는 기능이 제공됨_redirects파일을 공용 폴더에 저장하십시오.

단계:

  1. 이름이 지정된 파일 만들기_redirects에 공용으로
  2. 해당 파일에 이 코드 조각 줄 추가

코드 조각:

/* /index.html 200

여기서 자세히 읽어보십시오. https://docs.gitlab.com/ee/user/project/pages/redirects.html#rewrite-all-requests-to-a-root-indexhtml

2021 vue3 & vue-cli용 솔루션:

"기본 지침"을 사용하여 다음을 수행하십시오.

https://github.com/rafgraph/spa-github-pages#usage-instructions

바꿀 필요 없음var pathSegmentsToKeep = 0;.40410

그리고 그 다음엔vue.config.js:

  // do not use "./dist/"
  publicPath: "/dist/",
  // make the index.html file place at the root of the repo
  indexPath: "../index.html",

그럼 스파가 좋겠네~

참조URL: https://stackoverflow.com/questions/47677220/vuejs-history-mode-with-github-gitlab-pages

반응형