preview.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. // const connect = require('connect');
  18. // const serveStatic = require('serve-static');
  19. // const app = connect();
  20. app.use(staticServer(resolve(process.cwd(), viteConfig.outDir || 'dist')));
  21. portfinder.getPort(async (err, port) => {
  22. if (err) {
  23. throw err;
  24. } else {
  25. // const publicPath = process.env.BASE_URL;
  26. app.listen(port, function () {
  27. const empty = ' ';
  28. const common = `The preview program is already running:
  29. - LOCAL: http://localhost:${port}/
  30. - NETWORK: http://${getIPAddress()}:${port}/
  31. `;
  32. console.log(chalk.cyan('\n' + empty + common));
  33. });
  34. }
  35. });
  36. };
  37. const preview = async () => {
  38. const prompt = inquirer.prompt({
  39. type: 'list',
  40. message: 'Please select a preview method',
  41. name: 'type',
  42. choices: [
  43. {
  44. name: 'Preview after packaging',
  45. value: BUILD,
  46. },
  47. {
  48. name: `No packaging, preview directly (need to have dist file after packaging)`,
  49. value: NO_BUILD,
  50. },
  51. ],
  52. });
  53. const { type } = await prompt;
  54. if (type === BUILD) {
  55. await sh('npm run build', {
  56. async: true,
  57. nopipe: true,
  58. });
  59. }
  60. startApp();
  61. };
  62. (() => {
  63. preview();
  64. })();