DEPRECATED. It has been ported back to magic-string >= 0.26.0
Extended Rich-Harris/magic-string with extra utilities.
npm i magic-string-extra
magic-string-extra
can be a drop-in replacement for magic-string
:
- import MagicString from 'magic-string'
+ import MagicString from 'magic-string-extra'
Check magic-string
's documentation for the base utils.
Shares the same signature as String.prototype.replace
. Supports RegExp and replacer functions.
import MagicString from 'magic-string-extra'
const s = new MagicString(source)
s.replace(foo, 'bar')
s.replace(/foo/g, 'bar')
s.replace(/(\w)(\d+)/g, (_, $1, $2) => $1.toUpperCase() + $2)
The differences from String.replace
:
- It will always match against the original string
- It mutates the magic string state (use
.clone()
to be immutable)
In some cases, when the string does not change you might be able to skip the sourcemap generation to improve the performance (e.g. Rollup and Vite's transform hook). This function allows you to check the state without tracking it externally.
import MagicString from 'magic-string-extra'
const s = new MagicString(source)
s.hasChanged() // false
s.prepend('foo')
s.hasChanged() // true
It's common to use the magic string for code transformations in plugins. This function provides a shorthand to generate the result in Rollup's TransformResult
format. When the string has not changed, null
will be returned to skip the Rollup transformation.
import MagicString from 'magic-string-extra'
const s = new MagicString(source)
s.toRollupResult() // { code, map } | null
MIT License © 2022 Anthony Fu