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.

57 lines
1.5 KiB

4 years ago
  1. var through = require('through');
  2. var Visitor = require('./visitor');
  3. var recast = require('recast');
  4. var types = recast.types;
  5. /**
  6. * Transform an Esprima AST generated from ES6 by replacing all template string
  7. * nodes with the equivalent ES5.
  8. *
  9. * NOTE: The argument may be modified by this function. To prevent modification
  10. * of your AST, pass a copy instead of a direct reference:
  11. *
  12. * // instead of transform(ast), pass a copy
  13. * transform(JSON.parse(JSON.stringify(ast));
  14. *
  15. * @param {Object} ast
  16. * @return {Object}
  17. */
  18. function transform(ast) {
  19. return types.visit(ast, Visitor.visitor);
  20. }
  21. /**
  22. * Transform JavaScript written using ES6 by replacing all template string
  23. * usages with the equivalent ES5.
  24. *
  25. * compile('`Hey, ${name}!'); // '"Hey, " + name + "!"'
  26. *
  27. * @param {string} source
  28. * @param {{sourceFileName: string, sourceMapName: string}} mapOptions
  29. * @return {string}
  30. */
  31. function compile(source, mapOptions) {
  32. mapOptions = mapOptions || {};
  33. var recastOptions = {
  34. sourceFileName: mapOptions.sourceFileName,
  35. sourceMapName: mapOptions.sourceMapName
  36. };
  37. var ast = recast.parse(source, recastOptions);
  38. return recast.print(transform(ast), recastOptions);
  39. }
  40. module.exports = function() {
  41. var data = '';
  42. return through(write, end);
  43. function write(buf) { data += buf; }
  44. function end() {
  45. this.queue(module.exports.compile(data).code);
  46. this.queue(null);
  47. }
  48. };
  49. module.exports.compile = compile;
  50. module.exports.transform = transform;