serverPluginClient.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.clientPlugin = exports.clientPublicPath = exports.clientFilePath = void 0;
  7. const fs_1 = __importDefault(require("fs"));
  8. const path_1 = __importDefault(require("path"));
  9. const chalk_1 = __importDefault(require("chalk"));
  10. const config_1 = require("../config");
  11. exports.clientFilePath = path_1.default.resolve(__dirname, '../../client/client.js');
  12. exports.clientPublicPath = `/vite/client`;
  13. const legacyPublicPath = '/vite/hmr';
  14. exports.clientPlugin = ({ app, config }) => {
  15. const clientCode = fs_1.default
  16. .readFileSync(exports.clientFilePath, 'utf-8')
  17. .replace(`__MODE__`, JSON.stringify(config.mode || 'development'))
  18. .replace(`__DEFINES__`, JSON.stringify({
  19. ...config_1.defaultDefines,
  20. ...config.define
  21. }));
  22. app.use(async (ctx, next) => {
  23. if (ctx.path === exports.clientPublicPath) {
  24. let socketPort = ctx.port;
  25. // infer on client by default
  26. let socketProtocol = null;
  27. let socketHostname = null;
  28. if (config.hmr && typeof config.hmr === 'object') {
  29. // hmr option has highest priory
  30. socketProtocol = config.hmr.protocol || null;
  31. socketHostname = config.hmr.hostname || null;
  32. socketPort = config.hmr.port || ctx.port;
  33. if (config.hmr.path) {
  34. socketPort = `${socketPort}/${config.hmr.path}`;
  35. }
  36. }
  37. ctx.type = 'js';
  38. ctx.status = 200;
  39. ctx.body = clientCode
  40. .replace(`__HMR_PROTOCOL__`, JSON.stringify(socketProtocol))
  41. .replace(`__HMR_HOSTNAME__`, JSON.stringify(socketHostname))
  42. .replace(`__HMR_PORT__`, JSON.stringify(socketPort));
  43. }
  44. else {
  45. if (ctx.path === legacyPublicPath) {
  46. console.error(chalk_1.default.red(`[vite] client import path has changed from "/vite/hmr" to "/vite/client". ` +
  47. `please update your code accordingly.`));
  48. }
  49. return next();
  50. }
  51. });
  52. };
  53. //# sourceMappingURL=serverPluginClient.js.map