How to change Public Base Path in Vite asset handling for building for production

By Ravindra sharma 5 months ago

What is the problem to solve? What is base path. What is the use of it in production (dist) ?

With using Vite as the asset building and management, you come across whenever you try to build your project for a subdirectory or a folder point after a folder from / (root). Vite does create a path to the assets to the subdirectory instead, it just specifies the name right after / given in the example below.

Here is the below code assets is directly taken after / 

  <script type="module" crossorigin src="/assets/index-CbG3sSka.js"></script>
    <link rel="stylesheet" crossorigin href="/assets/index-B7XgWb8N.css">

 

 

GOAL : What we need to achieve. Let's say there is a subdirectory in which your portfolio page is kept which will be like domain.com/portfolio/, and you need to give it a portfolio related assets which will be like below.

    <script type="module" crossorigin src="/portfolio/assets/index-Dvet1d9S.js"></script>
    <link rel="stylesheet" crossorigin href="/portfolio/assets/index-BoZbVp80.css">

 

This problem is solved by specifying the public base path in Vite configuration file.

 

ProcedureVite configuration file (vite.config.js), you can use the base option. Used in deployment of your application to a subdirectory or setting a specific public path.

Here’s how to do it:

  1. Install Vite (if not already installed): If you haven't set up Vite yet.

npm install vite
npm install @vitejs/plugin-vue # If you're using Vue

 

     2. Create or Edit vite.config.js: Create a vite.config.js file in the root of your project if it doesn’t already exist. Then, add or edit the file to include the base option.

// vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue'; // If you're using Vue, otherwise import the relevant plugin

export default defineConfig({
  base: '/portfolio/', // Set the public base path here
  plugins: [vue()] // Add your plugins here
});

    

       3. Run Vite: To start the Vite development server, run:       

npm run dev

  For a production build, use:

npm run build

You will achieve production codes with /portfolio base path

 


Other Posts By Author

No Blogs yet!

Workflow

Web Dev, Applications Dev, Enterprenurship, Gen AI, AR/VR and More Related articles.

@copyrights 2022, All Rights Reserved