Reputation: 337
I have this svelte project where I implemented dynamic imports for the components FileSelector.svelte and TableViewer.svelte. Locally it works but when i build it and put it into an nginx webserver it still tries to fetch the components from the components directory which doesn't exist in the build dist-directory.
Codedescription: i have an array with the relative paths to the components. onMount I load the component with the mainComponentsArray with the index 0. When i wan't another component I just change the currComponent variable
Svelte code that implements dynamic imports:
<script>
import { currComponent } from './selectStore.js';
import { onMount } from "svelte";
import Footer from "./components/layout/Footer.svelte";
import Header from "./components/layout/Header.svelte";
let currentComponent;
const mainComponents = [
"./components/FileSelector.svelte",
"./components/TableViewer.svelte"
];
currComponent.subscribe((value) => {
changeComponent(value);
});
async function changeComponent(index) {
currentComponent = (await import(mainComponents[index])).default;
}
onMount(async () => {
currentComponent = (await import(mainComponents[0])).default;
});
</script>
<main>
<Header />
<div class="flex w-full flex-col items-center pt-5 pb-5 sm:p-5 lg:pt-10 lg:pb-10 lg:pl-32 lg:pr-32">
<svelte:component this={currentComponent} />
</div>
<Footer />
</main>
<style>
</style>
if needed vite config:
import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
export default defineConfig({
plugins: [svelte()],
server: {
host: true, port: 3000,
hmr: {
protocol: "ws"
}
}
})
if needed svelte.config
import preprocess from "svelte-preprocess";
const config = {
preprocess: [
preprocess({
postcss: true,
}),
],
};
export default config;
Upvotes: 1
Views: 2079
Reputation: 184296
The import paths probably have to be known at build time for this to work correctly, i.e. the argument to import()
has to be static.
I would try to do it like this instead:
const mainComponents = [
() => import("./components/FileSelector.svelte"),
() => import("./components/TableViewer.svelte")
];
Then you get the element by index and call the function to import.
Upvotes: 1