Challenges I encountered Configuring Vite for React Routing and Static File Integration

Day #17 of the #100DaysOfMiva coding challenge, I focused on resolving issues with Vite configuration, React routing, and static file handling for my personal website project. The goal was to ensure that the application could properly handle routing to…


This content originally appeared on DEV Community and was authored by TD!

Day #17 of the #100DaysOfMiva coding challenge, I focused on resolving issues with Vite configuration, React routing, and static file handling for my personal website project. The goal was to ensure that the application could properly handle routing to a static HTML page and resolve paths correctly.

Though I wasn't able to achieve my goal at the end but I learned tremendously in the process. If you have a better idea for what I was trying to accomplish, please put it in the comment, I'll try it and give feedback.

Challenge: The main issue was that clicking on the "Beyond Coding" link in the navigation did not direct me to the intended static HTML page (beyond-coding/index.html). Instead, the application attempted to route to #beyond-coding which wasn't what I wanted, maybe I made a mistake along the way, come with me.

Steps Taken:

Initial Issue: The Beyond Coding link in the navigation bar was set to #beyond-coding, which led to an incorrect URL: http://localhost:5173/#beyond-coding. The correct URL should have included the path to the static HTML file, such as http://localhost:5173/#beyond-coding/index.html.

Vite Configuration: I made adjustments to the Vite configuration file (vite.config.js) to address file serving and path resolution issues.

Initial Configuration Attempt:


import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  server: {
    fs: {
      allow: ['src', 'public'],
    }
  },
  plugins: [react()],
  assetsInclude: ['**/*.png', '**/*.jpg', '**/*.svg'],
});

Error Messages:

  • "Failed to load url /src/main.jsx (resolved id: C:/Dev/personal-website/src/main.jsx). Does the file exist?"

  • "The request url 'C:\Dev\personal-website\src\assets\logo.png' is outside of Vite serving allow list."

Correction:


import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  server: {
    fs: {
      allow: [
        'C:/Dev/personal-website/src', 
        'C:/Dev/personal-website/public', 
        'C:/Dev/personal-website/node_modules'
      ],
    }
  },
  plugins: [react()],
  assetsInclude: ['**/*.png', '**/*.jpg', '**/*.svg'],
});

React Component and Routing Issue: The Navbar component was initially set up to route to static HTML files directly. The correct approach was to use React Router to manage routing within the React application.

Original Navbar Code:


import React, { useState } from 'react';
import { Link } from 'react-router-dom';

import { styles } from '../styles.js';
import { navLinks } from '../constants';
import { logo, menu, close } from '../assets';

const Navbar = () => {
  const [active, setActive] = useState('');
  const [toggle, setToggle] = useState(false);

  return (
    <nav className={`${styles.paddingX} w-full flex items-center py-5 fixed top-0 z-20 bg-primary`}>
      <div className="w-full flex justify-between items-center max-w-7xl mx-auto">
        <Link to="/" className="flex items-center gap-2">
          <img src={logo} alt="logo" className="w-9 h-9 object-contain" />
          <p className="text-white text-[18px] font-bold cursor-pointer flex">
            TD! &nbsp; <span className="sm:block hidden">| &nbsp;Software Engineer</span>
          </p>
        </Link>
        <ul className="list-none hidden sm:flex flex-row gap-10">
          {navLinks.map(link => (
            <li
              key={link.id}
              className={`${active === link.title ? 'text-white' : 'text-secondary'} hover:text-white text-[18px] font-medium cursor-pointer`}
              onClick={() => setActive(link.title)}
            >
              <a href={`#${link.id}`}>{link.title}</a>
            </li>
          ))}
        </ul>
        <div className="sm:hidden flex flex-1 justify-end items-center">
          <img src={toggle ? close : menu} alt="menu" className="w-[28px] h-[28px] object-contain cursor-pointer" onClick={() => setToggle(!toggle)} />
          <div className={`${!toggle ? 'hidden' : 'flex'} p-6 black-gradient absolute top-20 right-0 mx-4 my-2 min-w-[140px] z-10 rounded-xl`}>
            <ul className="list-none flex sm:flex justify-end items-start flex-col gap-4">
              {navLinks.map(link => (
                <li
                  key={link.id}
                  className={`${active === link.title ? 'text-white' : 'text-secondary'} font-poppins font-medium cursor-pointer text-[16px]`}
                  onClick={() => {
                    setToggle(!toggle);
                    setActive(link.title);
                  }}
                >
                  <a href={`#${link.id}`}>{link.title}</a>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </div>
    </nav>
  );
};

export default Navbar;

Personal website landing page
If you noticed from the gif above, other links such as Work, About, Contact are working on the navbar link but Beyond Coding and Learn Coding, this is because they're different projects in separate folders but want to link them together so had to place them in the public directory, but even with that, it did not work.

Created a BeyondCodingRedirect component


import { useEffect } from 'react';

const BeyondCodingRedirect = () => {
  useEffect(() => {
    window.location.href = '/beyond-coding/index.html';
  }, []);

  return null;
};

export default BeyondCodingRedirect;

Included the link in the constants file

{
  id: 'beyond-coding',
  title: 'Beyond Coding',
  path: '/beyond-coding',
}

See routing -


import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import BeyondCodingRedirect from './components/BeyondCodingRedirect';
// other imports

function App() {
  return (
    <Router>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/work" element={<Work />} />
        <Route path="/contact" element={<Contact />} />
        <Route path="/beyond-coding" element={<BeyondCodingRedirect />} />
      </Routes>
    </Router>
  );
}

export default App;

Here's the link to the project on GitHub.

It's still a work in progress.

Please advice.


This content originally appeared on DEV Community and was authored by TD!


Print Share Comment Cite Upload Translate Updates
APA

TD! | Sciencx (2024-09-12T18:51:36+00:00) Challenges I encountered Configuring Vite for React Routing and Static File Integration. Retrieved from https://www.scien.cx/2024/09/12/challenges-i-encountered-configuring-vite-for-react-routing-and-static-file-integration/

MLA
" » Challenges I encountered Configuring Vite for React Routing and Static File Integration." TD! | Sciencx - Thursday September 12, 2024, https://www.scien.cx/2024/09/12/challenges-i-encountered-configuring-vite-for-react-routing-and-static-file-integration/
HARVARD
TD! | Sciencx Thursday September 12, 2024 » Challenges I encountered Configuring Vite for React Routing and Static File Integration., viewed ,<https://www.scien.cx/2024/09/12/challenges-i-encountered-configuring-vite-for-react-routing-and-static-file-integration/>
VANCOUVER
TD! | Sciencx - » Challenges I encountered Configuring Vite for React Routing and Static File Integration. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/09/12/challenges-i-encountered-configuring-vite-for-react-routing-and-static-file-integration/
CHICAGO
" » Challenges I encountered Configuring Vite for React Routing and Static File Integration." TD! | Sciencx - Accessed . https://www.scien.cx/2024/09/12/challenges-i-encountered-configuring-vite-for-react-routing-and-static-file-integration/
IEEE
" » Challenges I encountered Configuring Vite for React Routing and Static File Integration." TD! | Sciencx [Online]. Available: https://www.scien.cx/2024/09/12/challenges-i-encountered-configuring-vite-for-react-routing-and-static-file-integration/. [Accessed: ]
rf:citation
» Challenges I encountered Configuring Vite for React Routing and Static File Integration | TD! | Sciencx | https://www.scien.cx/2024/09/12/challenges-i-encountered-configuring-vite-for-react-routing-and-static-file-integration/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.