Home
Docs
GitHub
Pricing
Blog
Log In

Run Sandworm Audit for your App

Get started
Hold on, we're currently generating a fresh version of this report

magic-string 0.30.6

Modify strings, generate sourcemaps
Package summary
Share
0
issues
0
licenses
Package created
4 Nov 2014
Version published
31 Jan 2024
Maintainers
4
Total deps
0
Direct deps
0
License
MIT
Generating a report...
Hold on while we generate a fresh audit report for this package.

Frequently Asked Questions

What does magic-string do?

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.

How do you use magic-string?

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.

Where are the magic-string docs?

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.