| 1 | # magic-string
|
|---|
| 2 |
|
|---|
| 3 | <a href="https://travis-ci.org/Rich-Harris/magic-string">
|
|---|
| 4 | <img src="http://img.shields.io/travis/Rich-Harris/magic-string.svg"
|
|---|
| 5 | alt="build status">
|
|---|
| 6 | </a>
|
|---|
| 7 | <a href="https://npmjs.org/package/magic-string">
|
|---|
| 8 | <img src="https://img.shields.io/npm/v/magic-string.svg"
|
|---|
| 9 | alt="npm version">
|
|---|
| 10 | </a>
|
|---|
| 11 | <a href="https://github.com/Rich-Harris/magic-string/blob/master/LICENSE.md">
|
|---|
| 12 | <img src="https://img.shields.io/npm/l/magic-string.svg"
|
|---|
| 13 | alt="license">
|
|---|
| 14 | </a>
|
|---|
| 15 |
|
|---|
| 16 | Suppose you have some source code. You want to make some light modifications to it - replacing a few characters here and there, wrapping it with a header and footer, etc - and ideally you'd like to generate a source map at the end of it. You've thought about using something like [recast](https://github.com/benjamn/recast) (which allows you to generate an AST from some JavaScript, manipulate it, and reprint it with a sourcemap without losing your comments and formatting), but it seems like overkill for your needs (or maybe the source code isn't JavaScript).
|
|---|
| 17 |
|
|---|
| 18 | Your requirements are, frankly, rather niche. But they're requirements that I also have, and for which I made magic-string. It's a small, fast utility for manipulating strings and generating sourcemaps.
|
|---|
| 19 |
|
|---|
| 20 | ## Installation
|
|---|
| 21 |
|
|---|
| 22 | magic-string works in both node.js and browser environments. For node, install with npm:
|
|---|
| 23 |
|
|---|
| 24 | ```bash
|
|---|
| 25 | npm i magic-string
|
|---|
| 26 | ```
|
|---|
| 27 |
|
|---|
| 28 | To use in browser, grab the [magic-string.umd.js](https://unpkg.com/magic-string/dist/magic-string.umd.js) file and add it to your page:
|
|---|
| 29 |
|
|---|
| 30 | ```html
|
|---|
| 31 | <script src='magic-string.umd.js'></script>
|
|---|
| 32 | ```
|
|---|
| 33 |
|
|---|
| 34 | (It also works with various module systems, if you prefer that sort of thing - it has a dependency on [vlq](https://github.com/Rich-Harris/vlq).)
|
|---|
| 35 |
|
|---|
| 36 | ## Usage
|
|---|
| 37 |
|
|---|
| 38 | These examples assume you're in node.js, or something similar:
|
|---|
| 39 |
|
|---|
| 40 | ```js
|
|---|
| 41 | import MagicString from 'magic-string';
|
|---|
| 42 | import fs from 'fs'
|
|---|
| 43 |
|
|---|
| 44 | const s = new MagicString('problems = 99');
|
|---|
| 45 |
|
|---|
| 46 | s.overwrite(0, 8, 'answer');
|
|---|
| 47 | s.toString(); // 'answer = 99'
|
|---|
| 48 |
|
|---|
| 49 | s.overwrite(11, 13, '42'); // character indices always refer to the original string
|
|---|
| 50 | s.toString(); // 'answer = 42'
|
|---|
| 51 |
|
|---|
| 52 | s.prepend('var ').append(';'); // most methods are chainable
|
|---|
| 53 | s.toString(); // 'var answer = 42;'
|
|---|
| 54 |
|
|---|
| 55 | const map = s.generateMap({
|
|---|
| 56 | source: 'source.js',
|
|---|
| 57 | file: 'converted.js.map',
|
|---|
| 58 | includeContent: true
|
|---|
| 59 | }); // generates a v3 sourcemap
|
|---|
| 60 |
|
|---|
| 61 | fs.writeFileSync('converted.js', s.toString());
|
|---|
| 62 | fs.writeFileSync('converted.js.map', map.toString());
|
|---|
| 63 | ```
|
|---|
| 64 |
|
|---|
| 65 | You can pass an options argument:
|
|---|
| 66 |
|
|---|
| 67 | ```js
|
|---|
| 68 | const s = new MagicString(someCode, {
|
|---|
| 69 | // both these options will be used if you later
|
|---|
| 70 | // call `bundle.addSource( s )` - see below
|
|---|
| 71 | filename: 'foo.js',
|
|---|
| 72 | indentExclusionRanges: [/*...*/]
|
|---|
| 73 | });
|
|---|
| 74 | ```
|
|---|
| 75 |
|
|---|
| 76 | ## Methods
|
|---|
| 77 |
|
|---|
| 78 | ### s.addSourcemapLocation( index )
|
|---|
| 79 |
|
|---|
| 80 | Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is `false` (see below).
|
|---|
| 81 |
|
|---|
| 82 | ### s.append( content )
|
|---|
| 83 |
|
|---|
| 84 | Appends the specified content to the end of the string. Returns `this`.
|
|---|
| 85 |
|
|---|
| 86 | ### s.appendLeft( index, content )
|
|---|
| 87 |
|
|---|
| 88 | Appends the specified `content` at the `index` in the original string. If a range *ending* with `index` is subsequently moved, the insert will be moved with it. Returns `this`. See also `s.prependLeft(...)`.
|
|---|
| 89 |
|
|---|
| 90 | ### s.appendRight( index, content )
|
|---|
| 91 |
|
|---|
| 92 | Appends the specified `content` at the `index` in the original string. If a range *starting* with `index` is subsequently moved, the insert will be moved with it. Returns `this`. See also `s.prependRight(...)`.
|
|---|
| 93 |
|
|---|
| 94 | ### s.clone()
|
|---|
| 95 |
|
|---|
| 96 | Does what you'd expect.
|
|---|
| 97 |
|
|---|
| 98 | ### s.generateDecodedMap( options )
|
|---|
| 99 |
|
|---|
| 100 | Generates a sourcemap object with raw mappings in array form, rather than encoded as a string. See `generateMap` documentation below for options details. Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead.
|
|---|
| 101 |
|
|---|
| 102 | ### s.generateMap( options )
|
|---|
| 103 |
|
|---|
| 104 | Generates a [version 3 sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). All options are, well, optional:
|
|---|
| 105 |
|
|---|
| 106 | * `file` - the filename where you plan to write the sourcemap
|
|---|
| 107 | * `source` - the filename of the file containing the original source
|
|---|
| 108 | * `includeContent` - whether to include the original content in the map's `sourcesContent` array
|
|---|
| 109 | * `hires` - whether the mapping should be high-resolution. Hi-res mappings map every single character, meaning (for example) your devtools will always be able to pinpoint the exact location of function calls and so on. With lo-res mappings, devtools may only be able to identify the correct line - but they're quicker to generate and less bulky. If sourcemap locations have been specified with `s.addSourceMapLocation()`, they will be used here.
|
|---|
| 110 |
|
|---|
| 111 | The returned sourcemap has two (non-enumerable) methods attached for convenience:
|
|---|
| 112 |
|
|---|
| 113 | * `toString` - returns the equivalent of `JSON.stringify(map)`
|
|---|
| 114 | * `toUrl` - returns a DataURI containing the sourcemap. Useful for doing this sort of thing:
|
|---|
| 115 |
|
|---|
| 116 | ```js
|
|---|
| 117 | code += '\n//# sourceMappingURL=' + map.toUrl();
|
|---|
| 118 | ```
|
|---|
| 119 |
|
|---|
| 120 | ### s.indent( prefix[, options] )
|
|---|
| 121 |
|
|---|
| 122 | Prefixes each line of the string with `prefix`. If `prefix` is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. Returns `this`.
|
|---|
| 123 |
|
|---|
| 124 | The `options` argument can have an `exclude` property, which is an array of `[start, end]` character ranges. These ranges will be excluded from the indentation - useful for (e.g.) multiline strings.
|
|---|
| 125 |
|
|---|
| 126 | ### s.insertLeft( index, content )
|
|---|
| 127 |
|
|---|
| 128 | **DEPRECATED** since 0.17 – use `s.appendLeft(...)` instead
|
|---|
| 129 |
|
|---|
| 130 | ### s.insertRight( index, content )
|
|---|
| 131 |
|
|---|
| 132 | **DEPRECATED** since 0.17 – use `s.prependRight(...)` instead
|
|---|
| 133 |
|
|---|
| 134 | ### s.locate( index )
|
|---|
| 135 |
|
|---|
| 136 | **DEPRECATED** since 0.10 – see [#30](https://github.com/Rich-Harris/magic-string/pull/30)
|
|---|
| 137 |
|
|---|
| 138 | ### s.locateOrigin( index )
|
|---|
| 139 |
|
|---|
| 140 | **DEPRECATED** since 0.10 – see [#30](https://github.com/Rich-Harris/magic-string/pull/30)
|
|---|
| 141 |
|
|---|
| 142 | ### s.move( start, end, newIndex )
|
|---|
| 143 |
|
|---|
| 144 | Moves the characters from `start` and `end` to `index`. Returns `this`.
|
|---|
| 145 |
|
|---|
| 146 | ### s.overwrite( start, end, content[, options] )
|
|---|
| 147 |
|
|---|
| 148 | Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply. Returns `this`.
|
|---|
| 149 |
|
|---|
| 150 | The fourth argument is optional. It can have a `storeName` property — if `true`, the original name will be stored for later inclusion in a sourcemap's `names` array — and a `contentOnly` property which determines whether only the content is overwritten, or anything that was appended/prepended to the range as well.
|
|---|
| 151 |
|
|---|
| 152 | ### s.prepend( content )
|
|---|
| 153 |
|
|---|
| 154 | Prepends the string with the specified content. Returns `this`.
|
|---|
| 155 |
|
|---|
| 156 | ### s.prependLeft ( index, content )
|
|---|
| 157 |
|
|---|
| 158 | Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at `index`
|
|---|
| 159 |
|
|---|
| 160 | ### s.prependRight ( index, content )
|
|---|
| 161 |
|
|---|
| 162 | Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index`
|
|---|
| 163 |
|
|---|
| 164 | ### s.remove( start, end )
|
|---|
| 165 |
|
|---|
| 166 | Removes the characters from `start` to `end` (of the original string, **not** the generated string). Removing the same content twice, or making removals that partially overlap, will cause an error. Returns `this`.
|
|---|
| 167 |
|
|---|
| 168 | ### s.slice( start, end )
|
|---|
| 169 |
|
|---|
| 170 | Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string. Throws error if the indices are for characters that were already removed.
|
|---|
| 171 |
|
|---|
| 172 | ### s.snip( start, end )
|
|---|
| 173 |
|
|---|
| 174 | Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed.
|
|---|
| 175 |
|
|---|
| 176 | ### s.toString()
|
|---|
| 177 |
|
|---|
| 178 | Returns the generated string.
|
|---|
| 179 |
|
|---|
| 180 | ### s.trim([ charType ])
|
|---|
| 181 |
|
|---|
| 182 | Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end. Returns `this`.
|
|---|
| 183 |
|
|---|
| 184 | ### s.trimStart([ charType ])
|
|---|
| 185 |
|
|---|
| 186 | Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start. Returns `this`.
|
|---|
| 187 |
|
|---|
| 188 | ### s.trimEnd([ charType ])
|
|---|
| 189 |
|
|---|
| 190 | Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end. Returns `this`.
|
|---|
| 191 |
|
|---|
| 192 | ### s.trimLines()
|
|---|
| 193 |
|
|---|
| 194 | Removes empty lines from the start and end. Returns `this`.
|
|---|
| 195 |
|
|---|
| 196 | ### s.isEmpty()
|
|---|
| 197 |
|
|---|
| 198 | Returns true if the resulting source is empty (disregarding white space).
|
|---|
| 199 |
|
|---|
| 200 | ## Bundling
|
|---|
| 201 |
|
|---|
| 202 | To concatenate several sources, use `MagicString.Bundle`:
|
|---|
| 203 |
|
|---|
| 204 | ```js
|
|---|
| 205 | const bundle = new MagicString.Bundle();
|
|---|
| 206 |
|
|---|
| 207 | bundle.addSource({
|
|---|
| 208 | filename: 'foo.js',
|
|---|
| 209 | content: new MagicString('var answer = 42;')
|
|---|
| 210 | });
|
|---|
| 211 |
|
|---|
| 212 | bundle.addSource({
|
|---|
| 213 | filename: 'bar.js',
|
|---|
| 214 | content: new MagicString('console.log( answer )')
|
|---|
| 215 | });
|
|---|
| 216 |
|
|---|
| 217 | // Advanced: a source can include an `indentExclusionRanges` property
|
|---|
| 218 | // alongside `filename` and `content`. This will be passed to `s.indent()`
|
|---|
| 219 | // - see documentation above
|
|---|
| 220 |
|
|---|
| 221 | bundle.indent() // optionally, pass an indent string, otherwise it will be guessed
|
|---|
| 222 | .prepend('(function () {\n')
|
|---|
| 223 | .append('}());');
|
|---|
| 224 |
|
|---|
| 225 | bundle.toString();
|
|---|
| 226 | // (function () {
|
|---|
| 227 | // var answer = 42;
|
|---|
| 228 | // console.log( answer );
|
|---|
| 229 | // }());
|
|---|
| 230 |
|
|---|
| 231 | // options are as per `s.generateMap()` above
|
|---|
| 232 | const map = bundle.generateMap({
|
|---|
| 233 | file: 'bundle.js',
|
|---|
| 234 | includeContent: true,
|
|---|
| 235 | hires: true
|
|---|
| 236 | });
|
|---|
| 237 | ```
|
|---|
| 238 |
|
|---|
| 239 | As an alternative syntax, if you a) don't have `filename` or `indentExclusionRanges` options, or b) passed those in when you used `new MagicString(...)`, you can simply pass the `MagicString` instance itself:
|
|---|
| 240 |
|
|---|
| 241 | ```js
|
|---|
| 242 | const bundle = new MagicString.Bundle();
|
|---|
| 243 | const source = new MagicString(someCode, {
|
|---|
| 244 | filename: 'foo.js'
|
|---|
| 245 | });
|
|---|
| 246 |
|
|---|
| 247 | bundle.addSource(source);
|
|---|
| 248 | ```
|
|---|
| 249 |
|
|---|
| 250 | ## License
|
|---|
| 251 |
|
|---|
| 252 | MIT
|
|---|