Jony ive
Jony ive

Reputation: 121

Remove leading slash (/) from imports after bundling a Vite project

In my project, during dev everything works great but my target app seems to not parse imports that start with "/" properly ( I am developing for a local app, not for a website / webapp). How can I get Vite to ommit the / at the beginning of import statements only when building?

For example, if I have a file in my public folder that I import like so:

import something from '/file.svg

I need it to bundle as:

import something from 'assets/file.svg

But instead I am getting:

import something from '/assets/file.svg

I have tried modifying vite.config.js to include any of the following:

Upvotes: 8

Views: 1852

Answers (2)

Lukas Hillebrand
Lukas Hillebrand

Reputation: 436

I have tried with: "vite": "^6.0.5" and vite@latest.

but even setting base:'' sets always a slash(/) before the folder/filename like so:

<link rel="stylesheet" crossorigin="" href="/assets/main-DKYW8OEW.css">

what i want is:

<link rel="stylesheet" crossorigin="" href="assets/main-DKYW8OEW.css">

Upvotes: 2

hotenov
hotenov

Reputation: 1143

Check Vite version in your project. It seems there was an issue with base option in old versions.

I don't know the exact issue. But this one is related to base option. And it was fixed in 2022.

Update Vite and its plugins in your project and try again with empty string. (value ./ also works according to the Vite documentation).

Pay attention that you must specify the base option on top-level config object (NOT inside build option).

For example, this part of vite.config.js file demonstrates it:

export default defineConfig({
  plugins: [
    vue(),
  ],
  base: '',
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  build: {...

For Vite version 5.1.5 installed on my machine I get this result HTML file in the output (dist) folder:

enter image description here

Upvotes: 3

Related Questions