vite: The production environment uses new URL(src, import.meta.url) to report an error

Describe the bug

I can display pictures in the development environment, but import.meta.url after packaging is undefined, and cause the New URL to report.

I have already viewed other questions, most of them are previous versions, if it is a duplicate problem or my usage error, then I am very sorry!

Reproduction

https://github.com/RennCheung/import-meta-url-demo

System Info

System:
    OS: macOS 11.6
    CPU: (8) x64 Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
    Memory: 2.56 GB / 16.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 14.16.0 - /usr/local/bin/node
    Yarn: 1.22.10 - /usr/local/bin/yarn
    npm: 6.14.11 - /usr/local/bin/npm
  npmPackages:
    @vitejs/plugin-vue: ^1.9.4 => 1.9.4 
    @vitejs/plugin-vue-jsx: ^1.2.0 => 1.2.0 
    vite: ^2.6.13 => 2.6.13

Used Package Manager

pnpm

Logs

No response

Validations

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 1
  • Comments: 19 (10 by maintainers)

Most upvoted comments

This is because import.meta.url is not supported in Vite baseline target, so it will be undefined. It works in esnext build target.

@ydcjeff the build target has been set esnext,it still not work,and import.meta.url is undefined. Another, if build target is es2015, how do I dynamically reference image??

marking as documentation as i can understand from @ydcjeff this feature is statically analyzed which means variables can’t be used. reference to similar issue https://github.com/vitejs/vite/issues/5478