Blog>
Snippets

Creating Inline Source Maps

Provide an example of creating an inline source map by embedding it directly within the compiled JavaScript file.
const { SourceMapGenerator } = require('source-map');
const fs = require('fs');

// Your original code
const originalCode = `function hello() {\n  console.log('Hello, world!');\n}`;

// Your transformed code (e.g., transpiled/minified)
const transformedCode = `function hello(){console.log('Hello, world!');}`;

// Generate a source map
const map = new SourceMapGenerator({ file: 'output.js' });
map.addMapping({
  source: 'input.js',
  original: { line: 1, column: 0 },
  generated: { line: 1, column: 0 }
});
map.setSourceContent('input.js', originalCode);

// Convert source map to inline comment
const inlineSourceMap = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from(map.toString()).toString('base64')}`;

// Output the transformed code with inline source map
const codeWithInlineSourceMap = `${transformedCode}\n${inlineSourceMap}`;

// Write the result to a file
fs.writeFileSync('output.js', codeWithInlineSourceMap);
This code demonstrates how to generate a source map using the 'source-map' library and embed it inline in the transformed code. It requires the original and transformed code, generates the source map, converts it to Base64, and appends it as an inline comment to the transformed code. It then writes the code with the inline source map to an output file.