You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

206 lines
7.2 KiB

3 months ago
  1. # convert-source-map [![Build Status][ci-image]][ci-url]
  2. Converts a source-map from/to different formats and allows adding/changing properties.
  3. ```js
  4. var convert = require('convert-source-map');
  5. var json = convert
  6. .fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=')
  7. .toJSON();
  8. var modified = convert
  9. .fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=')
  10. .setProperty('sources', [ 'SRC/FOO.JS' ])
  11. .toJSON();
  12. console.log(json);
  13. console.log(modified);
  14. ```
  15. ```json
  16. {"version":3,"file":"build/foo.min.js","sources":["src/foo.js"],"names":[],"mappings":"AAAA","sourceRoot":"/"}
  17. {"version":3,"file":"build/foo.min.js","sources":["SRC/FOO.JS"],"names":[],"mappings":"AAAA","sourceRoot":"/"}
  18. ```
  19. ## Upgrading
  20. Prior to v2.0.0, the `fromMapFileComment` and `fromMapFileSource` functions took a String directory path and used that to resolve & read the source map file from the filesystem. However, this made the library limited to nodejs environments and broke on sources with querystrings.
  21. In v2.0.0, you now need to pass a function that does the file reading. It will receive the source filename as a String that you can resolve to a filesystem path, URL, or anything else.
  22. If you are using `convert-source-map` in nodejs and want the previous behavior, you'll use a function like such:
  23. ```diff
  24. + var fs = require('fs'); // Import the fs module to read a file
  25. + var path = require('path'); // Import the path module to resolve a path against your directory
  26. - var conv = convert.fromMapFileSource(css, '../my-dir');
  27. + var conv = convert.fromMapFileSource(css, function (filename) {
  28. + return fs.readFileSync(path.resolve('../my-dir', filename), 'utf-8');
  29. + });
  30. ```
  31. ## API
  32. ### fromObject(obj)
  33. Returns source map converter from given object.
  34. ### fromJSON(json)
  35. Returns source map converter from given json string.
  36. ### fromURI(uri)
  37. Returns source map converter from given uri encoded json string.
  38. ### fromBase64(base64)
  39. Returns source map converter from given base64 encoded json string.
  40. ### fromComment(comment)
  41. Returns source map converter from given base64 or uri encoded json string prefixed with `//# sourceMappingURL=...`.
  42. ### fromMapFileComment(comment, readMap)
  43. Returns source map converter from given `filename` by parsing `//# sourceMappingURL=filename`.
  44. `readMap` must be a function which receives the source map filename and returns either a String or Buffer of the source map (if read synchronously), or a `Promise` containing a String or Buffer of the source map (if read asynchronously).
  45. If `readMap` doesn't return a `Promise`, `fromMapFileComment` will return a source map converter synchronously.
  46. If `readMap` returns a `Promise`, `fromMapFileComment` will also return `Promise`. The `Promise` will be either resolved with the source map converter or rejected with an error.
  47. #### Examples
  48. **Synchronous read in Node.js:**
  49. ```js
  50. var convert = require('convert-source-map');
  51. var fs = require('fs');
  52. function readMap(filename) {
  53. return fs.readFileSync(filename, 'utf8');
  54. }
  55. var json = convert
  56. .fromMapFileComment('//# sourceMappingURL=map-file-comment.css.map', readMap)
  57. .toJSON();
  58. console.log(json);
  59. ```
  60. **Asynchronous read in Node.js:**
  61. ```js
  62. var convert = require('convert-source-map');
  63. var { promises: fs } = require('fs'); // Notice the `promises` import
  64. function readMap(filename) {
  65. return fs.readFile(filename, 'utf8');
  66. }
  67. var converter = await convert.fromMapFileComment('//# sourceMappingURL=map-file-comment.css.map', readMap)
  68. var json = converter.toJSON();
  69. console.log(json);
  70. ```
  71. **Asynchronous read in the browser:**
  72. ```js
  73. var convert = require('convert-source-map');
  74. async function readMap(url) {
  75. const res = await fetch(url);
  76. return res.text();
  77. }
  78. const converter = await convert.fromMapFileComment('//# sourceMappingURL=map-file-comment.css.map', readMap)
  79. var json = converter.toJSON();
  80. console.log(json);
  81. ```
  82. ### fromSource(source)
  83. Finds last sourcemap comment in file and returns source map converter or returns `null` if no source map comment was found.
  84. ### fromMapFileSource(source, readMap)
  85. Finds last sourcemap comment in file and returns source map converter or returns `null` if no source map comment was found.
  86. `readMap` must be a function which receives the source map filename and returns either a String or Buffer of the source map (if read synchronously), or a `Promise` containing a String or Buffer of the source map (if read asynchronously).
  87. If `readMap` doesn't return a `Promise`, `fromMapFileSource` will return a source map converter synchronously.
  88. If `readMap` returns a `Promise`, `fromMapFileSource` will also return `Promise`. The `Promise` will be either resolved with the source map converter or rejected with an error.
  89. ### toObject()
  90. Returns a copy of the underlying source map.
  91. ### toJSON([space])
  92. Converts source map to json string. If `space` is given (optional), this will be passed to
  93. [JSON.stringify](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify) when the
  94. JSON string is generated.
  95. ### toURI()
  96. Converts source map to uri encoded json string.
  97. ### toBase64()
  98. Converts source map to base64 encoded json string.
  99. ### toComment([options])
  100. Converts source map to an inline comment that can be appended to the source-file.
  101. By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would
  102. normally see in a JS source file.
  103. When `options.encoding == 'uri'`, the data will be uri encoded, otherwise they will be base64 encoded.
  104. When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file.
  105. ### addProperty(key, value)
  106. Adds given property to the source map. Throws an error if property already exists.
  107. ### setProperty(key, value)
  108. Sets given property to the source map. If property doesn't exist it is added, otherwise its value is updated.
  109. ### getProperty(key)
  110. Gets given property of the source map.
  111. ### removeComments(src)
  112. Returns `src` with all source map comments removed
  113. ### removeMapFileComments(src)
  114. Returns `src` with all source map comments pointing to map files removed.
  115. ### commentRegex
  116. Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments.
  117. Breaks down a source map comment into groups: Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data.
  118. ### mapFileCommentRegex
  119. Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments pointing to map files.
  120. ### generateMapFileComment(file, [options])
  121. Returns a comment that links to an external source map via `file`.
  122. By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would normally see in a JS source file.
  123. When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file.
  124. [ci-url]: https://github.com/thlorenz/convert-source-map/actions?query=workflow:ci
  125. [ci-image]: https://img.shields.io/github/workflow/status/thlorenz/convert-source-map/CI?style=flat-square