What is magic-string?
The magic-string package is a utility library designed for use in compilers and other tools that manipulate strings, particularly for source code transformations. It allows for efficient editing of string content, such as adding, replacing, and removing sections, while keeping track of original and modified positions. This is particularly useful for tasks like source map generation, code rewriting, and more.
What are magic-string's main functionalities?
Generate a source map
This feature demonstrates how to prepend and append content to a string and generate a source map for the transformation. It's useful for tracking changes between the original and transformed code.
const MagicString = require('magic-string');
let s = new MagicString('export var answer = 42;');
s.prepend('/* hello */\n').append('\n/* world */');
console.log(s.toString());
console.log(s.generateMap({ hires: true }));
Replace content
This feature shows how to replace a specific part of the string ('answer' with 'question'). It's particularly useful for code modifications where precise control over the text is needed.
const MagicString = require('magic-string');
let s = new MagicString('export var answer = 42;');
s.overwrite(12, 17, 'question');
console.log(s.toString());
Remove content
This feature illustrates how to remove a section of the string (the 'export ' part). It's useful for cleaning up or simplifying code by removing unnecessary parts.
const MagicString = require('magic-string');
let s = new MagicString('export var answer = 42;');
s.remove(0, 7);
console.log(s.toString());
Other packages similar to magic-string
recast
Recast is a JavaScript AST transformer that allows you to parse your code into an abstract syntax tree (AST), apply transformations to it, and then generate the modified code back. Unlike magic-string, which operates directly on strings, Recast works on a higher level of abstraction but can be more powerful for complex transformations.
escodegen
Escodegen is a code generator from an ESTree-compliant AST, similar to Recast in that it works with ASTs for code manipulation. While it doesn't offer the direct string manipulation capabilities of magic-string, it's useful for generating source code from ASTs, potentially after transformations have been applied.