vitejs / vite

Next generation frontend tooling. It's fast!
http://vite.dev
MIT License
68.09k stars 6.13k forks source link

Dynamic imported files not in built files #15864

Open karlhorky opened 8 months ago

karlhorky commented 8 months ago

Describe the bug

Files which are imported using Vite's dynamic import feature relying on an interpolated value (eg. from the define option) are not found after build:

main.ts

await import(`./x/${__NAME__}.ts`);

vite.config.ts

import { defineConfig } from 'vite';

export default defineConfig(({ mode }) => {
  return {
    build: { target: 'esnext' },
    define: {
      __NAME__: JSON.stringify('dynamic'),
    },
  };
});

Error message:

Uncaught TypeError: Failed to fetch dynamically imported module: http://localhost:8000/assets/x/dynamic.ts

The dynamically imported files are resolved in development mode.

Reproduction

https://github.com/karlhorky/vite-dynamic-import-build-missing-files

Steps to reproduce

  1. Use create-vite
  2. Add a define value
  3. Use the define value in a dynamic import in main.ts
  4. Run vite build
  5. Observe the error in the browser DevTools 💥

Alternative: clone repo above

System Info

System:
    OS: macOS 14.3.1
    CPU: (8) arm64 Apple M1
    Memory: 51.41 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.11.0 - /opt/homebrew/bin/node
    Yarn: 1.22.19 - /opt/homebrew/bin/yarn
    npm: 10.2.4 - /opt/homebrew/bin/npm
    pnpm: 8.15.1 - /opt/homebrew/bin/pnpm
  Browsers:
    Brave Browser: 111.1.49.120
    Chrome: 121.0.6167.160
    Chrome Canary: 123.0.6292.0
    Edge: 111.0.1661.44
    Safari: 17.3.1
  npmPackages:
    vite: ^5.1.0 => 5.1.1

Used Package Manager

pnpm

Logs

No response

Validations

karlhorky commented 8 months ago

Oh, after some searching I just found the following issue:

@bluwy is this related?

I will also post some details over there

XiSenao commented 8 months ago

You can use it as follows.

const fileName = __NAME__;
await import(`./x/${fileName}.ts`);

This may be related to the implementation of the @rollup/plugin-dynamic-import-vars plugin. ref: https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations