Improper source map attribution for JSON files
Describe the bug
When importing JSON files, the generated source map incorrectly attributes the JSON code to other modules. This leads to large parts of the bundle being assigned to unrelated files.
Originally reported in https://github.com/filipsobol/sonda/issues/175.
Reproduction
https://stackblitz.com/edit/vitejs-vite-ynptgptm
Steps to reproduce
- Visit the URL and wait for the project to build.
- Click "Download Project" button above the file tree and unzip the archive.
- Open Source Map Visualizer.
- Upload the
.jsand.js.mapfiles from thedist/assetsfolder. - Notice how the contents of the JSON file which make up the majority of the bundle are attributed to
../../src/data_1.jsinstead of../../src/data.json.
The also seems to depend on import order. For example, if in the reproduction project the JSON import is moved after the ./data_2.js import, rebuilt, and steps 2-6 are repeated, the JSON contents are instead attributed to ./data_2.js.
System Info
-
Used Package Manager
npm
Logs
No response
Validations
- [x] Follow our Code of Conduct
- [x] Read the Contributing Guidelines.
- [x] Read the docs.
- [x] Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- [x] Make sure this is a Vite issue and not a framework-specific issue. For example, if it's a Vue SFC related bug, it should likely be reported to vuejs/core instead.
- [x] Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- [x] The provided reproduction is a minimal reproducible example of the bug.
We currently don't generate sourcemaps for JSON files so the mapping for e=JSON.parse(...), part should've been a single length segment that signals not mapping to anything. Looks like right now the generated sourcemap by rollup skips over that and the e=JSON.parse(...), part gets included with the previous mapping.
Maybe worth checking if this is the case in a plain rollup setup.
Probably related to https://github.com/tc39/ecma426/issues/32
I wasn’t able to reproduce this in a plain Rollup setup using the @rollup/plugin-json plugin. Here’s an updated StackBlitz repro that includes both build:vite and build:rollup commands: https://stackblitz.com/edit/vitejs-vite-fzmfh8qd?file=package.json.
Interestingly, this issue only occurs in Vite when minification is enabled, regardless of whether build.minify is set to esbuild or terser. When build.minify is set to false, the generated source map appears to be correct.
If I add rollup-plugin-esbuild, it reproduces: https://stackblitz.com/edit/vitejs-vite-hql4d8dd?file=rollup.config.js
So I think the issue is in Rollup's sourcemap combine feature like https://github.com/rollup/rollup/issues/5955 and https://github.com/rollup/rollup/issues/5961.