joeldenning / vite-single-spa-example

MIT License
62 stars 25 forks source link

Assets are loaded from single spa url instead of microfrontends #13

Open Savuelo opened 2 years ago

Savuelo commented 2 years ago

I clone the project and run it without changing anything and microfrontend is unable to pull the assets from correct url. Microfrontend tries to fetch assets from root-config server instead of his own.

image
eduardojustos commented 2 years ago

I have the same issue. Opened it in the other repo for single spa and vite (https://github.com/joeldenning/vite-single-spa-root-config/issues/2)

justsanjit commented 2 years ago

I am facing the same issue. did you guys able to find a fix for this?

clabnet commented 2 years ago

+1

jones1008 commented 2 years ago

I found a solution:

Set the vite.config.js setting server.origin to the url of the application:

export default {
  ...
  server: {
    origin: 'http://localhost:3000',
  },
}

--> vite reference to server.origin: https://vitejs.dev/config/#server-origin

Additionally you need import the asset via javascript to get it's url. Apparently only then the url gets adjusted from vite automatically:

<script setup>
import logo from "./assets/logo.png"
</script>

<template>
  <img alt="Vue logo" :src="logo" />
  ...
</template>

Edit: I just noticed that for some reason, you have to reinstall the dependencies, so delete the pnpm-lock.yaml file and the node_modules folder and run pnpm install again

jones1008 commented 2 years ago

I even found a solution that does not need to import the asset via javascript but makes use of the resolve.alias config in vite:

import { fileURLToPath, URL } from 'url'

export default {
  ...
  server: {
    origin: 'http://localhost:3000',
  },
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
}

You can then import it with the @-syntax directly instead of via javascript and this automatically gets resolved to http://localhost:3000/src/assets/logo.png:

<template>
  <img alt="Vue logo" src="@/assets/logo.png" />
  ...
</template>

A relative path ./assets/logo.png will not work though

eduardojustos commented 2 years ago

@jones1008 the problem is that it also happens with bundles that were split. It could be a CSS bundle, an async Vue component that got into another bundle. And informing the URL it is going to be deployed sounds more like a quick fix and anti-pattern than a solution. Don't you think?

jones1008 commented 2 years ago

yes... you may be right... Maybe that problem won't appear in future Vite releases at all, if they move the prod build to ES modules too. See https://laurentcazanove.com/articles/state-of-vue-2022-amsterdam-recap/#a-note-on-vite-3 and https://github.com/vitejs/vite/pull/8178