magic-string
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
@jridgewell/sourcemap-codec | 1.4.15 | 8.72 kB | MIT | prod |
Magic-string is an open-source JavaScript utility that enables you to manipulate source code strings in an efficient way while also generating source maps. It is a perfect solution when you need to make light modifications to your source code and ideally generate a source map at the end. Useful for replacing characters, appending or prepending code snippets, and moving sections of code, the functionality provided by this utility covers a niche set of requirements for handling source code strings.
For using magic-string in your project, you need to install it using npm by running the command npm i magic-string
. Afterwards, follow this sample usage guide:
import MagicString from 'magic-string';
import fs from 'fs'
// Original string 'problems = 99'
const s = new MagicString('problems = 99');
// Replace 'problems' with 'answer'
s.update(0, 8, 'answer');
s.toString(); // 'answer = 99'
// Further replace '99' with '42'
s.update(11, 13, '42');
s.toString(); // 'answer = 42'
// Prepend and append to the string
s.prepend('var ').append(';');
s.toString(); // 'var answer = 42;'
// Generate a source map
const map = s.generateMap({
source: 'source.js',
file: 'converted.js.map',
includeContent: true
});
// Write the final string and map to file
fs.writeFileSync('converted.js', s.toString());
fs.writeFileSync('converted.js.map', map.toString());
The object MagicString
provides multiple methods for different operations such as append
, prepend
, trim
, remove
and more, providing a versatile toolset for any string manipulation needs.
The documentation for magic-string is embedded within the readme content on the package's GitHub repository. It provides a comprehensive guide to the utility's installation and usage, as well as a detailed description for each method available in the API of the MagicString
object. You can find this documentation at https://github.com/rich-harris/magic-string.