React Deploy Github Pages routes

COMPARTILHAR:

Whatsapp Telegram Twitter Facebook Reddit

Fix github.io gh-pages routes react js BrowserRouter

Para realizar deploy do front-end da sua aplicação React no Github Pages é muito simples. Primeiramente utilize o comando abaixo em seu projeto para instalar o gh-pages:

npm install --save-dev gh-pages

Em seguida precisamos realizar algumas configurações em seu arquivo package.json .

Adicione no inicio do arquivo, logo acima do nome do seu projeto a url em "homepage" do seu repositório no Github no formato de Github Pages. Exemplo:

[{

  "homepage": "http://user.github.io/repo",

  "name": "project name",

  "version": "0.1.0",

...]

*Substitua "user" pelo seu nome de usuário e "repo" pelo nome do repositório no Github.

Mais embaixo, no mesmo arquivo, em "Scripts" adicione o "predeploy" e "deploy" scripts ao seus scripts.

["scripts": {

    "predeploy": "npm run build",

    "deploy": "gh-pages -d build",

    "start": "react-scripts start",

    "build": "react-scripts build",

    "test": "react-scripts test",

    "eject": "react-scripts eject"

  },]

Agora basta rodar o comando "npm run deploy" (sem aspas) em seu terminal. Em seguida cheque a url "http://user.github.io/repo" para visualizar o seu projeto online.

Pode ser que você sofra com problemas de rotas (router) mostrando páginas em branco ou error 404. Para resolver isso, adicione "basename={process.env.PUBLIC_URL}" (sem aspas) ao seu "BrowserRouter". Exemplo:

[return (

        <BrowserRouter basename={process.env.PUBLIC_URL}>

            <Routes>

                <Route element={<Home/>} path="/" />

                <Route element={<SignUp />} path="/signup" />]

 Não esqueça de quando utilizar links em sua página os link tem que apontar corretamente:

[<a href={process.env.PUBLIC_URL + '/signup'} className="buttonSignup">]

Fazendo isso, deve resolver o problema para a página inicial, mas outras páginas devem persistir o problema de error 404, portanto é necessário fazer uma gambiarra. Copie o código abaixo, ou clicando aqui, e crie um arquivo denominado 404.html dentro do diretório "public" do seu projeto. Altere a variável "pathSegmentsToKeep" para 1 caso utilize um domínio personalizado ou para 0 caso use domínio padrão do github.

[<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    <title>Single Page Apps for GitHub Pages</title>
    <script type="text/javascript">
      // Single Page Apps for GitHub Pages
      // MIT License
      // https://github.com/rafgraph/spa-github-pages
      // This script takes the current url and converts the path and query
      // string into just a query string, and then redirects the browser
      // to the new url with only a query string and hash fragment,
      // e.g. https://www.foo.tld/one/two?a=b&c=d#qwe, becomes
      // https://www.foo.tld/?/one/two&a=b~and~c=d#qwe
      // Note: this 404.html file must be at least 512 bytes for it to work
      // with Internet Explorer (it is currently > 512 bytes)

      // If you're creating a Project Pages site and NOT using a custom domain,
      // then set pathSegmentsToKeep to 1 (enterprise users may need to set it to > 1).
      // This way the code will only replace the route part of the path, and not
      // the real directory in which the app resides, for example:
      // https://username.github.io/repo-name/one/two?a=b&c=d#qwe becomes
      // https://username.github.io/repo-name/?/one/two&a=b~and~c=d#qwe
      // Otherwise, leave pathSegmentsToKeep as 0.
      var pathSegmentsToKeep = 0;

      var l = window.location;
      l.replace(
        l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
        l.pathname.split('/').slice(0, 1 + pathSegmentsToKeep).join('/') + '/?/' +
        l.pathname.slice(1).split('/').slice(pathSegmentsToKeep).join('/').replace(/&/g, '~and~') +
        (l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +
        l.hash
      );

    </script>
  </head>
  <body>
  </body>
</html>]

Em seguida abra o arquivo index.html, que está dentro do diretório "public" e adicione o trecho de código abaixo no inicio do head do seu código, antes das tags meta.

[<script type="text/javascript">

        // Single Page Apps for GitHub Pages

        // MIT License

        // https://github.com/rafgraph/spa-github-pages

        // This script checks to see if a redirect is present in the query string,

        // converts it back into the correct url and adds it to the

        // browser's history using window.history.replaceState(...),

        // which won't cause the browser to attempt to load the new url.

        // When the single page app is loaded further down in this file,

        // the correct url will be waiting in the browser's history for

        // the single page app to route accordingly.

        (function (l) {

            if (l.search[1] === '/') {

                var decoded = l.search.slice(1).split('&').map(function (s) {

                    return s.replace(/~and~/g, '&')

                }).join('?');

                window.history.replaceState(null, null,

                    l.pathname.slice(0, -1) + decoded + l.hash

                );

            }

        }(window.location))

    </script>]

Pronto, agora basta rodar o comando "npm run deploy" (sem aspas) em seu terminal. Em seguida cheque a url "http://user.github.io/repo" para visualizar o seu projeto online.

COMENTÁRIOS

Nome

#ann,25,#HK,30,#LTCode,126,Artigo - Diversos,156,Artigo - Games,200,Artigo - Tecnologia,598,autor-thomaz,7,Coluna - Alternative World,24,Coluna - Fail,12,Coluna - Tec Line,14,Criptomoeda,71,Curiosidades - Diversos,49,Curiosidades - Tecnologia,50,en,2,estudo,8,HN,12,logica,14,Pentest,23,Programar C,29,Programar POO,6,Programar Python,6,Programar Shell,21,Programar verilog,12,Raspberry Pi,15,Redes,3,root,101,Shorty Awards,1,Smartphones - Reviews,33,Teoria,10,Top Nostalgia,2,VPN,18,WhatsApp,46,
ltr
item
Limon Tec: React Deploy Github Pages routes
React Deploy Github Pages routes
Fix github.io gh-pages routes react js BrowserRouter
https://blogger.googleusercontent.com/img/a/AVvXsEi89iWGo4RRu_OIwtqx-qao5WKaAANEhyKfcten3hDE9C7MfNJUIQpcK0x_IrlE1nnuD9EGMY0b6iga1rq4Pw2ZrQWvDVegmG2zXwHI_KZXgPNJcU5P4A7cCNt0BQ1e-QshJuIZKzPNbMIURJHGg_CnqwtemhwB4HKRx7bpxBPbcX_6jLJXg3svpELWww=w640-h218
https://blogger.googleusercontent.com/img/a/AVvXsEi89iWGo4RRu_OIwtqx-qao5WKaAANEhyKfcten3hDE9C7MfNJUIQpcK0x_IrlE1nnuD9EGMY0b6iga1rq4Pw2ZrQWvDVegmG2zXwHI_KZXgPNJcU5P4A7cCNt0BQ1e-QshJuIZKzPNbMIURJHGg_CnqwtemhwB4HKRx7bpxBPbcX_6jLJXg3svpELWww=s72-w640-c-h218
Limon Tec
https://www.limontec.com/2022/01/react-deploy-github-pages-routes.html
https://www.limontec.com/
https://www.limontec.com/
https://www.limontec.com/2022/01/react-deploy-github-pages-routes.html
false
2157924926610706248
UTF-8
Carregar todos posts Não encontramos nenhum post VER TUDO Ler mais Responder Cancelar resposta Deletar Por Home PÁGINAS POSTS Ver tudo RECOMENDADO PARA VOCÊ LABEL ARQUIVO SEARCH TODOS POSTS Não encontramos nenhum post relacionado a sua requisição VOLTAR PÁGINA INICIAL Domingo Segunda Terça Quarta Quinta Sexta Sábado Dom Seg Ter Qua Qui Sex Sab Janeiro Fevereiro Março Abril Maio Junho Julho Agosto Setembro Outubro Novembro Dezembro Jan Fev Mar Abr Maio Jun Jul Ago Set Out Nov Dez apenas agora 1 minuto atrás $$1$$ minutes ago 1 hora atrás $$1$$ hours ago Ontem $$1$$ days ago $$1$$ weeks ago mais de 5 semanas atrás Seguidores Seguir ESTE CONTEÚDO ESTÁ BLOQUEADO PASSO 1: Compartilhe com seus amigos PASSO 2: Clique no link compartilhado Copiar Todo Código Selecionar Todo Código Todos códigos foram copiados para seu clipboard Não é possível copiar códigos / textos, por favor aperte [CTRL]+[C] (ou CMD+C no Mac) para copiar Tabela de conteúdo