preview.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import chalk from 'chalk';
  2. import Koa from 'koa';
  3. import inquirer from 'inquirer';
  4. import { sh } from 'tasksfile';
  5. import staticServer from 'koa-static';
  6. import portfinder from 'portfinder';
  7. import { resolve } from 'path';
  8. import viteConfig from '../../vite.config';
  9. import { getIPAddress } from '../utils';
  10. const BUILD = 1;
  11. const NO_BUILD = 2;
  12. // 启动服务器
  13. const startApp = () => {
  14. const port = 9680;
  15. portfinder.basePort = port;
  16. const app = new Koa();
  17. app.use(staticServer(resolve(process.cwd(), viteConfig.outDir || 'dist')));
  18. portfinder.getPort(async (err, port) => {
  19. if (err) {
  20. throw err;
  21. } else {
  22. // const publicPath = process.env.BASE_URL;
  23. app.listen(port, function () {
  24. const empty = ' ';
  25. const common = `The preview program is already running:
  26. - LOCAL: http://localhost:${port}/
  27. - NETWORK: http://${getIPAddress()}:${port}/
  28. `;
  29. console.log(chalk.cyan('\n' + empty + common));
  30. });
  31. }
  32. });
  33. };
  34. const preview = async () => {
  35. const prompt = inquirer.prompt({
  36. type: 'list',
  37. message: 'Please select a preview method',
  38. name: 'type',
  39. choices: [
  40. {
  41. name: 'Preview after packaging',
  42. value: BUILD,
  43. },
  44. {
  45. name: `No packaging, preview directly (need to have dist file after packaging)`,
  46. value: NO_BUILD,
  47. },
  48. ],
  49. });
  50. const { type } = await prompt;
  51. if (type === BUILD) {
  52. await sh('npm run build', {
  53. async: true,
  54. nopipe: true,
  55. });
  56. }
  57. startApp();
  58. };
  59. (() => {
  60. preview();
  61. })();