index.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { createNodeMiddleware } from './node/';
  2. import { buildMswForBrowser, createBrowserMiddleware } from './browser/vitePlugin';
  3. import type { HttpHandler } from 'msw';
  4. import type { PluginOption } from 'vite';
  5. export interface VitePluginMswOptions {
  6. mode?: 'browser' | 'node';
  7. handlers?: HttpHandler[];
  8. build?: boolean;
  9. }
  10. interface BrowserIntegrationOptions {
  11. build?: boolean;
  12. }
  13. const browserIntegration = ({ build }: BrowserIntegrationOptions): PluginOption => {
  14. let outDir;
  15. return {
  16. name: 'vite-plugin-msw:browser-integration',
  17. configureServer(devServer) {
  18. const { isProduction } = devServer.config;
  19. if (!isProduction) {
  20. devServer.middlewares.use(createBrowserMiddleware());
  21. }
  22. },
  23. configResolved(config) {
  24. outDir = config.build.outDir;
  25. },
  26. async closeBundle() {
  27. const isProduction = process.env.NODE_ENV === 'production';
  28. if (isProduction && build) {
  29. await buildMswForBrowser({ outDir });
  30. }
  31. },
  32. };
  33. };
  34. const getNodeIntegration = (handlers: HttpHandler[]): PluginOption => {
  35. return {
  36. name: 'vite-plugin-msw:node-integration',
  37. configureServer(devServer) {
  38. devServer.middlewares.use(createNodeMiddleware()(...handlers));
  39. },
  40. };
  41. };
  42. function vitePluginMsw(
  43. options: Omit<VitePluginMswOptions, 'handlers'> & { mode?: 'browser' },
  44. ): PluginOption;
  45. function vitePluginMsw(options: VitePluginMswOptions): PluginOption {
  46. const { mode = 'browser', handlers = [], build = false } = options;
  47. if (mode === 'node') {
  48. return getNodeIntegration(handlers);
  49. } else {
  50. return browserIntegration({ build });
  51. }
  52. }
  53. export default vitePluginMsw;