vite: `new URL(foo, import.meta.url)` doesn't work when dependency was optimized

Describe the bug

Now, i use wasm-pack for build WASM file and WASM with JavaScript glue layer like this。

The glue layer code contains below code


if (typeof input === 'undefined') {
165 | input = new URL('color_thief_wasm_bg.wasm', import.meta.url);
166 | }

In Vite, after esbuild optimize third party, import.meta.url cannot be optimize succeed. Ref Vite Docs, even if set build.target to es2020 is still the problem

After preprocess

node_modules/color-thief-wasm-web/color_thief_wasm.js will be transform to node_modules/.vite/deps/color_thief_wasm.js which load .wasm file by import.meta.url receive incorrect path is node_modules/.vite/deps/xxx.wasm finally, the correct path is node_modules/color-thief-wasm-web/xxx.wasm

One of the solutions is set optimizeDeps.exclude to exclude third party module like this

Reproduction

https://stackblitz.com/edit/vite-rkrfzu?file=src%2FApp.vue,vite.config.js

System Info

vite@2.9.9

Used Package Manager

npm

Logs

Failed to construct 'URL': Invalid URL

Validations

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 33
  • Comments: 19 (5 by maintainers)

Commits related to this issue

Most upvoted comments

Got a similar issue:

const template = new URL('./some.txt', import.meta.url)
return readFileSync(template, 'utf-8')

Results in

const s = new URL("data:text/plain;base64,...", self.location);
return g(s, "utf-8");

With the error self is not defined.

Leaving some notes about the current status of this issue.

optimizeDeps.exclude workaround works when just starting vite. But not for vite build unfortunately, the wasm file gets excluded. Was there another workaround for the build side?

OK, adding assetsInclude: ["**/argon2id/dist/*.wasm"] worked.

Is this the same issue on esbuild?

In short: import.meta.url is not transformed so, when modules are bundled into a single location, the expected .url has changed.

Input

// file at ./foo/bar.js
export default import.meta.url; // should be /full/foo/bar.js
// file at ./index.js
import url from './foo/bar.js';
console.log(url); // should still be /full/foo/bar.js

Output

// file at ./dist/index.js
const barDefaultExport = import.meta.url;
console.log(barDefaultExport);

which prints full/dist/index.js instead of /full/dist/foo/bar.js

An ugly practice is move wasm package to current project rather than node_modules for get correct path