From:  James Burke <jrburke@gmail.com>
Date:  15 Oct 2013 04:21:48 Hong Kong Time
Newsgroup:  news.mozilla.org/mozilla.dev.js-sourcemap
Subject:  

Correct approach for bundles that contain more than original source

NNTP-Posting-Host:  24.86.26.209

With the requirejs optimizer, one way to get a source map is to combine multiple files together into one file. The source map is then for mapping from the bundle file back to the original files.

However, part of the combination of files, I normally add a '\n' between files, to help avoid any ASI issues. Those line breaks are not part of the original sources.

I am using the https://github.com/mozilla/source-map 0.1.30 library to build the source maps.

I thought I had a solution for this (looked fine in a source map visualization tool[1]), but for some cases, UglifyJS2 gives a warning when it consumes the source map for its use in generating the final bundle -> minified map:

    WARN: Couldn't figure out mapping for bundle.js:1,1 → 1,1 []

My understanding is that source maps support the bundle file having segments that do not map back to a file that is mapped. 

So I want to confirm that what I am doing is correct use of the API for skipping the added \n between bundled files. If so, then I will contact the UglifyJS2 project to see if there is a bug on its consumption of the source map for their own source map generation.

What I am doing now:

var sourceMapGenerator = new SourceMapGenerator.SourceMapGenerator({ file: ... });

// Holds the bundled contents.
var bundleContents = '';

//For each single file that will go in the bundle,
//whose location is stored in sourceMapPath, 
//read its contents into singleContents
//and do the following:

  //Find the starting line number in the bundleContents
  //for use in the map. Add 1 to skip the \n that will end
  //up in the bundle, but not part of mapping to single
  //file sources
  var sourceMapLineNumber = bundleContents.split('\n').length - 1 + 1;

  // Remove the starting \n inserted by the tool, as that
  // does not show up in the original single file source
  var mapSingleContents = singleContents.substring(1);
  var lineCount = mapSingleContents.split('\n').length;

  // Map each line 
  for (var i = 1; i <= lineCount; i += 1) {
    sourceMapGenerator.addMapping({
      generated: {
        line: sourceMapLineNumber + i,
        column: 0
      },
      original: {
        line: i,
        column: 0
      },
      source: sourceMapPath
    });
  }

  //Store the content of the singleContents, but without the line break
  sourceMapGenerator.setSourceContent(sourceMapPath, mapSingleContents);

  //Add the file to the final contents
  bundleContents += singleContents;

//end for loop over single file contents.

Thank you,
James

[1] http://sokra.github.io/source-map-visualization/