javascriptreactjsvitesource-mapsjavascript-debugger

Vite build.sourcemap hidden not loading in Chrome or Firefox


Migrating my react app from create-react-app to Vite and seeing some unexpected behavior with source maps. Vite docs regarding source maps are here. I was leaning toward using sourcemap: true until I saw that sourcemap: 'hidden' is the same thing except it is supposed to hide my comments ... sounds like exactly what I want.

If I create a build with sourcemap: true, each JS file gets its own map file, and the JS file gets a comment like //# sourceMappingURL=mylibrary-033b4774.js.map appended at the end of it. The source maps get loaded into Chrome and Firefox as expected.

If I create a build with sourcemap: 'hidden', the only difference in output is that the //# sourceMappingURL=mylibrary-033b4774.js.map comment is NOT appended at the end of the JS file. A map file is still produced for each JS file, and it is accessible if I try to access it manually in the browser by typing its full path. However, the browsers don't seem to like this ... they don't show the map at all.

Is this a bug in Vite or am I doing something wrong here?


Solution

  • Solution

    This is an expected behaviour, by which the source map will be only fetched by the browser when the comment //# sourceMappingURL= is present and the user is in the dev tools.

    Example

    Behind the scenes, it will attach the value of sourceMappingURL with the current URL.

    1. If //# sourceMappingURL=build.js.map is your EOF and http://localhost:3000 your localhost URL, then the browser will fetch http://localhost:3000/build.js.map
    2. If //# sourceMappingURL=http://localhost:8080/build.js.map is your EOF, then the browser will try to fetch sourcemap from http://localhost:3000/build.js.map

    Generally, we conditionally add the source map in the build as

    sourcemap: process.ENV === 'production' ? 'hidden' : true;
    

    Additionally

    1. Adding sourcemap in production env may lead to security issues, as you are exposing your actual code to the browser.
    2. If you want to add it anyway, make sure to host sourcemap with a CORS policy on custom URL, for which you can configure something like below
        build: {
          rollupOptions: {
            output: {
              sourcemap: true,
              sourcemapBaseUrl: 'YOUR SOURCEMAP BASE URL', // https://www.my-source-maps.com
            }
          }
        }
    

    for this refer the following links

    a. Vite Config on how to use custom rollup settings https://vitejs.dev/config/build-options.html#build-sourcemap

    b. Read out how to configure the rollup https://rollupjs.org/configuration-options/#output-sourcemap