Skip to content

Instantly share code, notes, and snippets.

@bmeurer
Created March 3, 2023 08:32
Show Gist options
  • Save bmeurer/df2c2a08e0d4828edc270c35a276ac0c to your computer and use it in GitHub Desktop.
Save bmeurer/df2c2a08e0d4828edc270c35a276ac0c to your computer and use it in GitHub Desktop.
import MagicString from 'magic-string';
import open from 'open';
function magic_string_replace_all(src, search, replace) {
let idx = src.original.indexOf(search);
if (idx == -1) throw new Error('search not found in src');
do {
src.update(idx, idx + search.length, replace, {storeName: true});
} while ((idx = src.original.indexOf(search, idx + 1)) != -1);
}
const input = `h1 {
--replace-me-once: red;
}
h2 {
--replace-me-twice: green;
}
div {
--keep-me: blue;
}`;
const src = new MagicString(input);
magic_string_replace_all(src, '--replace-me-once', '\n --done-replace-once');
magic_string_replace_all(
src, '--replace-me-twice', '\n--almost-done-replace-twice');
const map = src.generateMap({hires: true});
const code = src.toString();
const url = 'https://sokra.github.io/source-map-visualization/#base64,' + [
code, JSON.stringify(map)
].concat(input).map(s => btoa(unescape(encodeURIComponent(s))));
open(url);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment