index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import path from 'path';
  2. import fs from 'fs';
  3. export function NodeGlobalsPolyfillPlugin({ buffer = false, define = {}, process = true, } = {}) {
  4. return {
  5. name: 'node-globals-polyfill',
  6. setup({ initialOptions, onResolve, onLoad }) {
  7. onResolve({ filter: /_node-buffer-polyfill_\.js/ }, (arg) => {
  8. return {
  9. path: path.resolve(__dirname, '../Buffer.js'),
  10. };
  11. });
  12. onResolve({ filter: /_node-process-polyfill_\.js/ }, (arg) => {
  13. return {
  14. path: path.resolve(__dirname, '../process.js'),
  15. };
  16. });
  17. onLoad({ filter: /_virtual-process-polyfill_\.js/ }, (arg) => {
  18. const data = fs
  19. .readFileSync(path.resolve(__dirname, '../process.js'))
  20. .toString();
  21. const keys = Object.keys(define);
  22. return {
  23. loader: 'js',
  24. contents: data.replace(`const defines = {}`, 'const defines = {\n' +
  25. keys
  26. .filter((x) => x.startsWith('process.'))
  27. .sort((a, b) => a.length - b.length)
  28. .map((k) => ` ${JSON.stringify(k).replace('process.', '')}: ${define[k]},`)
  29. .join('\n') +
  30. '\n}'),
  31. };
  32. });
  33. const polyfills = [];
  34. if (process) {
  35. polyfills.push(path.resolve(__dirname, '../_virtual-process-polyfill_.js'));
  36. }
  37. if (buffer) {
  38. polyfills.push(path.resolve(__dirname, '../_buffer.js'));
  39. }
  40. if (initialOptions.inject) {
  41. initialOptions.inject.push(...polyfills);
  42. }
  43. else {
  44. initialOptions.inject = [...polyfills];
  45. }
  46. },
  47. };
  48. }
  49. export default NodeGlobalsPolyfillPlugin;
  50. //# sourceMappingURL=index.js.map