vue.jsvite

How to set vite.config.js base public path?


I'm trying to set a base url for both my dev and prod environments, but vitejs configs are not resolved.

According to vitejs , you can set the base public path when served in development or production, in your config options.

When running vite from the command line, Vite will automatically try to resolve a config file named vite.config.js inside project root.

The issue is that my application requests don't go through 'http://localhost:8080/', but are still appended to the default serving port http://localhost:3000/.

My current configs are bellow:

// vite.config.js
export default {
  base: 'http://localhost:8080/'
}
// packages.json
{
  "name": "vue3ui",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build"
  },
  "dependencies": {
    ...,
    "vue": "^3.0.11"
  },
  "devDependencies": {
    "@vue/compiler-sfc": "^3.0.11",
    "vite": "^1.0.0-rc.13"
  }
}

Solution

  • Not totally clear to me but I will try to give you an answer to achieve what you want.

    I'm trying to set a base url for both my dev and prod environments

    Edit: I read again you question, and I think you are looking for the point C on this answer.

    Changes should be made in vite.config.js

    A) You are looking to change the running port from 3000 to 8080, adjust server.port

    server: {
      port: '8080'
    }
    

    B) But if you are looking to run on localhost:3000 and forward requests to localhost:8080 then you have to adjust server.proxy

    server: {
        proxy: {
          '/': {
            target: 'http://localhost:8080/'
          },
    
          '/admin': {
            target: 'http://localhost:8081/'
          }
        }
      }
    

    example:

    • '/': will proxy all requests to localhost:8080
    • '/admin': will proxy only requests that have as endpoint /admin to http://localhost:8081

    C) Changing base path depending on dev or prod environment

    .env file :

    // .env
     
    // Running locally
    APP_ENV=local
    // you change port of local/dev here to :8000
    // do not forget to adjust `server.port`
    ASSET_URL=http://localhost:3000
     
    // Running production build
    APP_ENV=production
    ASSET_URL=https://your-prod-asset-domain.com
    

    vite.config.js:

    const ASSET_URL = process.env.ASSET_URL || '';
    
    export default { 
      base: `${ASSET_URL}/dist/`,
    
      [...]
    }
    

    If it's not what you are looking for, please be more precise and I will edit my answer.

    For more information, head to the official doc at https://vitejs.dev/config/#server-options