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

1

8

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:

  • base: '',
  • base: '/',
  • base: './',
Corpus answered 1/5, 2023 at 13:11 Comment(0)
A
2

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

Allineallis answered 22/3 at 7:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.