gulp-processImportsToEs6.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Dependencies.
  2. var through = require('through2');
  3. var PluginError = require('plugin-error');
  4. let fs = require('fs');
  5. /**
  6. * Replace all imports by their corresponding ES6 imports.
  7. */
  8. function processImports(sourceCode, replacements) {
  9. for (let replacement of replacements) {
  10. var regex = new RegExp(`(["'])${replacement.packageName}([/"'])`, "g");
  11. sourceCode = sourceCode.replace(regex, `$1${replacement.newPackageName}$2`);
  12. }
  13. return sourceCode;
  14. }
  15. /**
  16. * Replaces all imports by their es6 peers.
  17. */
  18. function main(replacements) {
  19. return through.obj(function (file, enc, cb) {
  20. if (file.isNull()) {
  21. cb(null, file);
  22. return;
  23. }
  24. if (file.isStream()) {
  25. cb(new PluginError("Process Imports", "Streaming not supported."));
  26. }
  27. let data = file.contents.toString();
  28. data = processImports(data, replacements);
  29. // Go to disk.
  30. fs.writeFileSync(file.path, data);
  31. return cb();
  32. });
  33. }
  34. module.exports = main;