transform.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. "use strict";
  2. const babel = require("@babel/core");
  3. const {
  4. promisify
  5. } = require("util");
  6. const LoaderError = require("./Error");
  7. const transform = promisify(babel.transform);
  8. module.exports = async function (source, options) {
  9. let result;
  10. try {
  11. result = await transform(source, options);
  12. } catch (err) {
  13. throw err.message && err.codeFrame ? new LoaderError(err) : err;
  14. }
  15. if (!result) return null;
  16. // We don't return the full result here because some entries are not
  17. // really serializable. For a full list of properties see here:
  18. // https://github.com/babel/babel/blob/main/packages/babel-core/src/transformation/index.js
  19. // For discussion on this topic see here:
  20. // https://github.com/babel/babel-loader/pull/629
  21. const {
  22. ast,
  23. code,
  24. map,
  25. metadata,
  26. sourceType,
  27. externalDependencies
  28. } = result;
  29. if (map && (!map.sourcesContent || !map.sourcesContent.length)) {
  30. map.sourcesContent = [source];
  31. }
  32. return {
  33. ast,
  34. code,
  35. map,
  36. metadata,
  37. sourceType,
  38. // Convert it from a Set to an Array to make it JSON-serializable.
  39. externalDependencies: Array.from(externalDependencies || [])
  40. };
  41. };
  42. module.exports.version = babel.version;