antfu / vite-ssg

Static site generation for Vue 3 on Vite

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[vite:asset-import-meta-url] `new URL(url, import.meta.url)` is not supported in SSR.

netopolit opened this issue · comments

I am trying to pass image name to a child component and use it to create an URL to use as a background image on HTML element.
My approach was passing image name as a prop imgName to a component. In the receiving component I'm doing this:

<script>
  props: {
    imgName: {
      type: String,
      required: true,
    },
  },

  data() {
    return {
       imgUrl: "",
    }
  },
  
  created() {
    this.imgUrl = `url(${new URL(`../assets/images/${this.imgName}`, import.meta.url).href})`
  },
</script>

<style>
  .element {
    ...
    background-image: v-bind(imgUrl);
    ...
}
</style>

This approach works in dev environment but when creating a production bundle I get this error [vite-plugin-pwa] new URL(url, import.meta.url) is not supported in SSR.

Any idea how I can generate image URL that will work both on the dev server and for production bundle using SSR?

Thank you.

@netopolit try mounted instead created

@netopolit try mounted instead created

I still get the same error on running pnpm run build. I don't think lifecycle hook is the culprit. I think SSR build just doesn't support new URL(url, import.meta.url). Maybe there is a workaround for this, maybe an alternative approach.

@netopolit if you're using the assets directory all asset names will include the hash since vite will transform them: maybe you can move them to public directory or to a custom directory inside assets folder, then you can use import.meta.glob/globEager in a custom module and them map the key and the url (like the src/modules/i18n.ts module on vitesse) or add a virtual module to resolve them using for example fast-glob.

@netopolit reviwing the vite docs, import.meta.url is not supported, does not work with SSR, see last warning on the following entry: https://vitejs.dev/guide/assets.html#new-url-url-import-meta-url

Thanks @userquin. Does anyone have any suggestion how to pass concatenated image url as a prop so it works with SSR?
Thanks for the effort.

@netopolit if the image is known you can just pass it from parent just using the import (change the sfc to use that url instead build the url):

// parent component
<script>
import img from '<relative_to_parent_assets_dir>/assets/a.png'
</script>
<template>
  <ImgComp :img-url="img"/>
</template>

If the image is not known you should add a module with the logic containing the images map and exporting them: just provide a repro since it is not clear how are you using the images. It is similar using the url on the img html tag, vite will take care for you to change the url, you don't need to do some special logic for it: in your case instead using the img html tag you're using a sfc.