module-map.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. 'use strict';
  8. var PluginError = require('plugin-error');
  9. var through = require('through2');
  10. var fs = require('fs');
  11. var path = require('path');
  12. var PM_REGEXP = require('./shared/provides-module').regexp;
  13. var PLUGIN_NAME = 'module-map';
  14. module.exports = function(opts) {
  15. // Assume file is a string for now
  16. if (!opts || !('moduleMapFile' in opts && 'prefix' in opts)) {
  17. throw new PluginError(
  18. PLUGIN_NAME,
  19. 'Missing options. Ensure you pass an object with `moduleMapFile` and `prefix`'
  20. );
  21. }
  22. var moduleMapFile = opts.moduleMapFile;
  23. var prefix = opts.prefix;
  24. var moduleMap = {};
  25. function transform(file, enc, cb) {
  26. if (file.isNull()) {
  27. cb(null, file);
  28. return;
  29. }
  30. if (file.isStream()) {
  31. cb(new PluginError('module-map', 'Streaming not supported'));
  32. return;
  33. }
  34. // Get the @providesModule piece of out the file and save that.
  35. var matches = file.contents.toString().match(PM_REGEXP);
  36. if (matches) {
  37. var name = matches[1];
  38. if (moduleMap.hasOwnProperty(name)) {
  39. this.emit(
  40. 'error',
  41. new PluginError(
  42. PLUGIN_NAME,
  43. 'Duplicate module found: ' + name + ' at ' + file.path + ' and ' +
  44. moduleMap[name]
  45. )
  46. );
  47. }
  48. moduleMap[name] = file.path;
  49. }
  50. this.push(file);
  51. cb();
  52. }
  53. function flush(cb) {
  54. // Keep it ABC order for better diffing.
  55. var map = Object.keys(moduleMap).sort().reduce(function(prev, curr) {
  56. // Rewrite path here since we don't need the full path anymore.
  57. prev[curr] = prefix + path.basename(moduleMap[curr], '.js');
  58. return prev;
  59. }, {});
  60. fs.writeFile(moduleMapFile, JSON.stringify(map, null, 2), 'utf-8', function() {
  61. // avoid calling cb with fs.write callback data
  62. cb();
  63. });
  64. }
  65. return through.obj(transform, flush);
  66. };