sveltejs / svelte

Cybernetically enhanced web apps
https://svelte.dev
MIT License
77.43k stars 4.03k forks source link

Dynamic import not working with (group) advanced routing #12023

Open shinokada opened 2 weeks ago

shinokada commented 2 weeks ago

Describe the bug

I'm not sure if this is a bug. I use the following code for [slug] dir:

// [slug]/+page.js
/** @type {import('./$types').PageLoad} */
export async function load({ params }) {
  const post = await import(`../${params.slug}.svelte`);
  const content = post.default;
  // console.log('dir-2', content)
  return {
    content
  };
}

// +page.svelte
<script lang="ts">
  import type { PageData } from './$types';
  export let data: PageData;
</script>

<svelte:component this={data.content} />

I have exactly the same directories except one has a group routing:

├── (app)
│   └── dir-1
│       ├── [slug]
│       │   ├── +page.js
│       │   └── +page.svelte
│       └── test.svelte
├── +page.svelte
└── dir-2
    ├── [slug]
    │   ├── +page.js
    │   └── +page.svelte
    └── test.svelte

dir-2 works but dir-1 returns the following error:

Error: Unknown variable dynamic import: ../../../(app)/dir-1/test.svelte
    at dynamic-import-helper.js:7:96
    at new Promise (<anonymous>)
    at default (dynamic-import-helper.js:6:12)
    at load (+page.js:3:22)
    at load_node (client.js?v=c8e2c5a3:717:39)

Reproduction

git clone git@github.com:shinokada/svelte-issue.git
pnpm i && pnpm dev

Go to http://localhost:5173/dir-2/test to see it is working. Go to http://localhost:5173/dir-1/test to see the error.

Logs

No response

System Info

System:
    OS: macOS 14.5
    CPU: (10) arm64 Apple M2 Pro
    Memory: 221.25 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.14.0 - ~/.nvm/versions/node/v20.14.0/bin/node
    npm: 10.7.0 - ~/.nvm/versions/node/v20.14.0/bin/npm
    pnpm: 9.3.0 - /opt/homebrew/bin/pnpm
    bun: 1.1.8 - ~/.bun/bin/bun
  Browsers:
    Chrome: 126.0.6478.57
    Edge: 125.0.2535.92
    Safari: 17.5

Severity

annoyance

paoloricciuti commented 2 weeks ago
  1. this is a sveltekit issue and not a svelte issue
  2. when providing a reproduction try to create something runnable, it's easier for the maintainers this way...i created one for you
  3. if you take a look at the output of the build (the files should already be open when you open the sveltelab link) you can see how you +page.ts is transformed and where the error originates. However this is most likely an issue with vite and how it transforms the dynamic import. So i would actually move this issue in vite. I think parens kinda messes with the vite transform.
7nik commented 2 weeks ago

Shouldn't glob import be used in such cases?

paoloricciuti commented 2 weeks ago

Shouldn't glob import be used in such cases?

It's also an option but if you know that you just want to import a single file in an upper folder why bother with glob? Also if you remove parens it works so imho it's a bug in vite.