I tried setting up gitlab pages with my react app but it's showing me 404 error

I tried setting up gitlab pages with my react app, however, I'm unable to do it as it's not generating any url for me to go to. I've set up gitlab-ci.yml.

> image: node:latest
pages:
  script:
    - npm install
    - npm run build
    - mkdir public2
    - mv public/* public2
  artifacts:
    paths:
      - public2
  only:
    - master
  stage: deploy

Upvotes: 2

Views: 2812

Answers (2)

Yuci
Yuci

Reputation: 30089

An example of setting up Gitlab pages for a React app:

Step 1: I created a React project and pushed to gitlab

$ npx create-react-app hello-react

This is repo: https://gitlab.com/ygou/hello-react

Step 2: Created .gitlab-ci.yml as shown below

https://gitlab.com/ygou/hello-react/blob/master/.gitlab-ci.yml

# Using the node alpine image to build the React app
image: node:alpine

# Announce the URL as per CRA docs
# https://create-react-app.dev/docs/advanced-configuration/
variables:
  PUBLIC_URL: /hello-react

# Cache node modules - speeds up future builds
cache:
  paths:
  - node_modules

# Name the stages involved in the pipeline
stages:
- deploy

# Job name for gitlab to recognise this results in assets for Gitlab Pages
# https://docs.gitlab.com/ee/user/project/pages/introduction.html#gitlab-pages-requirements
pages:
  stage: deploy
  script:
    - npm install # Install all dependencies
    - npm run build # Build for production
    - cp public/index.html public/404.html # Not necessary, but helps with https://medium.com/@pshrmn/demystifying-single-page-applications-3068d0555d46
    - mv public _public # CRA and gitlab pages both use the public folder. Only do this in a build pipeline.
    - mv build public # Move build files to public dir for Gitlab Pages
  artifacts:
    paths:
    - public # The built files for Gitlab Pages to serve
  only:
    - master # Only run on master branch

Job done

Once the CI/CD job has finished, you can see the Gitlab pages for the React app:

https://ygou.gitlab.io/hello-react/

Reference: https://ohmybuck.com/2018-08-12-build-a-react-website-with-full-cicd-in-two-minutes/

Upvotes: 7

Trevor Michaelis
Trevor Michaelis

Reputation: 1

I am pretty sure that

artifacts:
    paths:
      - public2

needs to be

artifacts:
    paths:
      - public

So you could also remove the - mv public/* public2 command the build will succeed but the deploy will fail unless the path is public.

Upvotes: 0

Related Questions