index.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. const {ProvidePlugin} = require('webpack');
  3. const filterObject = require('filter-obj');
  4. function createAliasFilter({includeAliases, excludeAliases}) {
  5. if (includeAliases.length > 0) {
  6. return object => filterObject(object, key => includeAliases.includes(key));
  7. }
  8. return object => filterObject(object, key => !excludeAliases.includes(key));
  9. }
  10. module.exports = class NodePolyfillPlugin {
  11. constructor(options = {}) {
  12. this.options = {
  13. excludeAliases: [],
  14. includeAliases: [],
  15. ...options
  16. };
  17. if (this.options.includeAliases.length > 0 && this.options.excludeAliases.length > 0) {
  18. throw new Error('excludeAliases and includeAliases are mutually exclusive');
  19. }
  20. }
  21. apply(compiler) {
  22. const filter = createAliasFilter(this.options);
  23. compiler.options.plugins.push(new ProvidePlugin(filter({
  24. Buffer: [require.resolve('buffer/'), 'Buffer'],
  25. console: require.resolve('console-browserify'),
  26. process: require.resolve('process/browser')
  27. })));
  28. compiler.options.resolve.fallback = {
  29. ...filter({
  30. assert: require.resolve('assert/'),
  31. buffer: require.resolve('buffer/'),
  32. console: require.resolve('console-browserify'),
  33. constants: require.resolve('constants-browserify'),
  34. crypto: require.resolve('crypto-browserify'),
  35. domain: require.resolve('domain-browser'),
  36. events: require.resolve('events/'),
  37. http: require.resolve('stream-http'),
  38. https: require.resolve('https-browserify'),
  39. os: require.resolve('os-browserify/browser'),
  40. path: require.resolve('path-browserify'),
  41. punycode: require.resolve('punycode/'),
  42. process: require.resolve('process/browser'),
  43. querystring: require.resolve('querystring-es3'),
  44. stream: require.resolve('stream-browserify'),
  45. /* eslint-disable camelcase */
  46. _stream_duplex: require.resolve('readable-stream/lib/_stream_duplex'),
  47. _stream_passthrough: require.resolve('readable-stream/lib/_stream_passthrough'),
  48. _stream_readable: require.resolve('readable-stream/lib/_stream_readable'),
  49. _stream_transform: require.resolve('readable-stream/lib/_stream_transform'),
  50. _stream_writable: require.resolve('readable-stream/lib/_stream_writable'),
  51. string_decoder: require.resolve('string_decoder/'),
  52. /* eslint-enable camelcase */
  53. sys: require.resolve('util/'),
  54. timers: require.resolve('timers-browserify'),
  55. tty: require.resolve('tty-browserify'),
  56. url: require.resolve('url/'),
  57. util: require.resolve('util/'),
  58. vm: require.resolve('vm-browserify'),
  59. zlib: require.resolve('browserify-zlib')
  60. }),
  61. ...compiler.options.resolve.fallback
  62. };
  63. }
  64. };