index.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*!
  2. * babel-extract-comments <https://github.com/jonschlinkert/babel-extract-comments>
  3. *
  4. * Copyright (c) 2014-2018, Jon Schlinkert.
  5. * Released under the MIT License.
  6. */
  7. 'use strict';
  8. const fs = require('fs');
  9. const path = require('path');
  10. const babylon = require('babylon');
  11. /**
  12. * Extract code comments from the given `string`.
  13. *
  14. * ```js
  15. * var extract = require('babel-extract-comments');
  16. * console.log(extract('// this is a code comment'));
  17. * // [{ type: 'CommentBlock',
  18. * // value: '!\n * babel-extract-comments <https://github.com/jonschlinkert/babel-extract-comments>\n *\n *
  19. * // Copyright (c) 2014-2018, Jon Schlinkert.\n * Released under the MIT License.\n ',
  20. * // start: 0,
  21. * // end: 173,
  22. * // loc: SourceLocation { start: [Position], end: [Position] } }]
  23. * ```
  24. * @param {String} `string` String of javascript
  25. * @return {Array} Array of code comment objects.
  26. * @api public
  27. */
  28. function extract(str, options) {
  29. const res = babylon.parse(str, options);
  30. return res.comments;
  31. }
  32. /**
  33. * Extract code comments from a JavaScript file.
  34. *
  35. * ```js
  36. * console.log(extract.file('some-file.js'), { cwd: 'some/path' });
  37. * // [ { type: 'Line',
  38. * // value: ' this is a line comment',
  39. * // range: [ 0, 25 ],
  40. * // loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 25 } } } ]
  41. * ```
  42. * @param {String} `file` Filepath to the file to parse.
  43. * @param {Object} `options` Options to pass to [esprima][].
  44. * @return {Array} Array of code comment objects.
  45. * @api public
  46. */
  47. extract.file = function(file, options) {
  48. const opts = Object.assign({ cwd: process.cwd() }, options);
  49. const str = fs.readFileSync(path.resolve(opts.cwd, file), 'utf8');
  50. return extract(str, options);
  51. };
  52. /**
  53. * Expose `extract`
  54. */
  55. module.exports = extract;