File size: 90,899 Bytes
25f22bf |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 |
======================== CODE SNIPPETS ======================== TITLE: Create and Start Vite Dev Server DESCRIPTION: Demonstrates how to programmatically create a Vite development server instance using `createServer` and start it with `listen`. It also shows how to print server URLs. SOURCE: https://vite.dev/index LANGUAGE: javascript CODE: ``` import { createServer } from 'vite' const server = await createServer({ // user config options }) await server.listen() server.printUrls() ``` ---------------------------------------- TITLE: Install and Deploy with Netlify CLI DESCRIPTION: Commands to install the Netlify CLI globally, initialize a new Netlify site, and deploy the project. The `--prod` flag is used for production deployments. SOURCE: https://vite.dev/guide/static-deploy LANGUAGE: bash CODE: ``` # Install the Netlify CLI $ npm install -g netlify-cli # Create a new site in Netlify $ ntl init # Deploy to a unique preview URL $ ntl deploy # Deploy the site into production $ ntl deploy --prod ``` ---------------------------------------- TITLE: Framework-Specific Vite Starters DESCRIPTION: Direct commands to create starter projects for popular frameworks, leveraging Vite. These provide optimized setups for specific ecosystems. SOURCE: https://vite.dev/blog/announcing-vite6 LANGUAGE: bash CODE: ``` create-vue ``` LANGUAGE: bash CODE: ``` npx nuxi init ``` LANGUAGE: bash CODE: ``` npm create svelte@latest my-app ``` LANGUAGE: bash CODE: ``` npx create-remix@latest ``` LANGUAGE: bash CODE: ``` npx create-analog@latest ``` LANGUAGE: bash CODE: ``` ng new my-app --style=scss --standalone=false ``` ---------------------------------------- TITLE: Vite Lightning CSS Setup DESCRIPTION: Explains how to enable experimental support for Lightning CSS as a CSS transformer and minifier in Vite. This requires installing the `lightningcss` package and configuring Vite's build options. SOURCE: https://vite.dev/guide/features LANGUAGE: bash CODE: ``` npm add -D lightningcss ``` LANGUAGE: json CODE: ``` // vite.config.js // For transformer: export default { css: { transformer: 'lightningcss' } } // For minifier: export default { build: { cssMinify: 'lightningcss' } } ``` ---------------------------------------- TITLE: Build and Link Vite from Source DESCRIPTION: Steps to clone the Vite repository, build it locally, and link it globally for development. Requires pnpm for installation and linking. SOURCE: https://vite.dev/guide LANGUAGE: bash CODE: ``` git clone https://github.com/vitejs/vite.git cd vite pnpm install cd packages/vite pnpm run build pnpm link --global # use your preferred package manager for this step ``` ---------------------------------------- TITLE: Vite Server Environment Setup DESCRIPTION: Example of setting up Vite server environments, specifically configuring a worker environment. This involves creating a custom environment factory that manages communication with a worker process. SOURCE: https://vite.dev/guide/api-environment-runtimes LANGUAGE: js CODE: ``` import { BroadcastChannel } from 'node:worker_threads' import { createServer, RemoteEnvironmentTransport, DevEnvironment } from 'vite' function createWorkerEnvironment(name, config, context) { const worker = new Worker('./worker.js') const handlerToWorkerListener = new WeakMap() const workerHotChannel = { send: (data) => worker.postMessage(data), on: (event, handler) => { if (event === 'connection') return const listener = (value) => { if (value.type === 'custom' && value.event === event) { const client = { send(payload) { worker.postMessage(payload) }, } handler(value.data, client) } } handlerToWorkerListener.set(handler, listener) worker.on('message', listener) }, off: (event, handler) => { if (event === 'connection') return const listener = handlerToWorkerListener.get(handler) if (listener) { worker.off('message', listener) handlerToWorkerListener.delete(handler) } }, } return new DevEnvironment(name, config, { transport: workerHotChannel, }) } await createServer({ environments: { worker: { dev: { createEnvironment: createWorkerEnvironment, }, }, }, }) ``` ---------------------------------------- TITLE: Vite Preview Configuration Example DESCRIPTION: Example of how to configure Vite's preview server options within the vite.config.js file. This demonstrates setting custom ports for both the development server and the preview server. SOURCE: https://vite.dev/config/preview-options LANGUAGE: js CODE: ``` export default defineConfig({ server: { port: 3030, }, preview: { port: 8080, }, }) ``` ---------------------------------------- TITLE: Preview Vite Build Output DESCRIPTION: To resolve CORS errors when opening built HTML files directly via the 'file' protocol, serve the build output using a local HTTP server. The `vite preview` command starts a local server for previewing your production build. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: bash CODE: ``` npx vite preview ``` ---------------------------------------- TITLE: ModuleRunner Example Usage DESCRIPTION: Demonstrates how to instantiate and use the ModuleRunner with an ESModulesEvaluator and a transport implementation. It shows the basic setup for importing a module. SOURCE: https://vite.dev/guide/api-environment-runtimes LANGUAGE: javascript CODE: ``` import { ModuleRunner, ESModulesEvaluator } from 'vite/module-runner' import { transport } from './rpc-implementation.js' const moduleRunner = new ModuleRunner( { transport, }, new ESModulesEvaluator(), ) await moduleRunner.import('/src/entry-point.js') ``` ---------------------------------------- TITLE: Create Vite App DESCRIPTION: Scaffolds a new Vite project with your preferred framework. Use this command to quickly start a new Vite-based application. SOURCE: https://vite.dev/blog/announcing-vite6 LANGUAGE: bash CODE: ``` pnpm create vite ``` ---------------------------------------- TITLE: Install Vite from Unreleased Commits DESCRIPTION: Installs a specific commit of Vite from the pkg.pr.new service, allowing testing of unreleased features. Requires replacing 'SHA' with a valid commit hash. SOURCE: https://vite.dev/guide LANGUAGE: bash CODE: ``` $ npm install -D https://pkg.pr.new/vite@SHA ``` LANGUAGE: bash CODE: ``` $ yarn add -D https://pkg.pr.new/vite@SHA ``` LANGUAGE: bash CODE: ``` $ pnpm add -D https://pkg.pr.new/vite@SHA ``` LANGUAGE: bash CODE: ``` $ bun add -D https://pkg.pr.new/vite@SHA ``` ---------------------------------------- TITLE: Vite Playground with vite.new DESCRIPTION: Access Vite 4 playgrounds online by visiting vite.new. This is useful for quickly testing Vite with different frameworks without local setup. SOURCE: https://vite.dev/blog/announcing-vite4 LANGUAGE: bash CODE: ``` vite.new ``` ---------------------------------------- TITLE: Run Vite Development Server DESCRIPTION: Commands to start the Vite development server using different package managers. The server serves the index.html file and hot-reloads changes. SOURCE: https://vite.dev/guide LANGUAGE: bash CODE: ``` $ npx vite ``` LANGUAGE: bash CODE: ``` $ yarn vite ``` LANGUAGE: bash CODE: ``` $ pnpm vite ``` LANGUAGE: bash CODE: ``` $ bunx vite ``` LANGUAGE: bash CODE: ``` $ deno run -A npm:vite ``` ---------------------------------------- TITLE: Vite Server Warmup Configuration DESCRIPTION: Configuration example for Vite's `server.warmup` option in `vite.config.js`. This pre-transforms and caches specified client files to improve startup performance and reduce request waterfalls. SOURCE: https://vite.dev/guide/performance LANGUAGE: javascript CODE: ``` import { defineConfig } from 'vite'; export default defineConfig({ server: { warmup: { clientFiles: [ './src/components/BigComponent.vue', './src/utils/big-utils.js', ], }, }, }); ``` ---------------------------------------- TITLE: Scaffold Vite Project (with Template) DESCRIPTION: Commands to create a new Vite project and specify a framework template directly. This allows for immediate setup of projects like Vite + Vue or Vite + React. SOURCE: https://vite.dev/guide LANGUAGE: bash CODE: ``` # npm 7+, extra double-dash is needed: $ npm create vite@latest my-vue-app -- --template vue ``` LANGUAGE: bash CODE: ``` $ yarn create vite my-vue-app --template vue ``` LANGUAGE: bash CODE: ``` $ pnpm create vite my-vue-app --template vue ``` LANGUAGE: bash CODE: ``` $ bun create vite my-vue-app --template vue ``` LANGUAGE: bash CODE: ``` $ deno init --npm vite my-vue-app --template vue ``` ---------------------------------------- TITLE: Deploy to xmit DESCRIPTION: Deploy your static site using xmit Static Site Hosting by following their specific guide for Vite projects. SOURCE: https://vite.dev/guide/static-deploy LANGUAGE: shell CODE: ``` # Follow xmit's Vite quickstart guide for deployment steps. ``` ---------------------------------------- TITLE: Example Library Entry File DESCRIPTION: This JavaScript file serves as an entry point for a library. It imports components or modules (e.g., Foo.vue, Bar.vue) and exports them, making them available for users who import the library package. SOURCE: https://vite.dev/guide/build LANGUAGE: js CODE: ``` import Foo from './Foo.vue' import Bar from './Bar.vue' export { Foo, Bar } ``` ---------------------------------------- TITLE: Vite Dev Server Commands DESCRIPTION: Commands and options for starting the Vite development server. This includes specifying the root directory, host, port, and other server behaviors. SOURCE: https://vite.dev/guide/cli LANGUAGE: APIDOC CODE: ``` vite dev [root] vite serve [root] Starts Vite dev server in the current directory. `vite dev` and `vite serve` are aliases. Parameters: root: The root directory of the project (optional). Options: --host [host] Specify hostname (string). Example: --host 0.0.0.0 --port <port> Specify port (number). Example: --port 3000 --open [path] Open browser on startup (boolean | string). Example: --open Example: --open /about --cors Enable CORS (boolean). --strictPort Exit if specified port is already in use (boolean). --force Force the optimizer to ignore the cache and re-bundle (boolean). -c, --config <file> Use specified config file (string). Example: -c vite.config.ts --base <path> Public base path (default: '/'). Example: --base /app/ -l, --logLevel <level> Set log level (info | warn | error | silent). Example: -l warn --clearScreen Allow/disable clear screen when logging (boolean). --configLoader <loader> Use 'bundle' to bundle the config with esbuild, or 'runner' (experimental) to process it on the fly, or 'native' (experimental) to load using the native runtime (default: 'bundle'). Example: --configLoader runner --profile Start built-in Node.js inspector (check [Performance bottlenecks](/guide/troubleshooting#performance-bottlenecks)). -d, --debug [feat] Show debug logs (string | boolean). Example: -d optimize Example: -d true -f, --filter <filter> Filter debug logs (string). Example: -f plugin-name -m, --mode <mode> Set env mode (string). Example: -m production -h, --help Display available CLI options. -v, --version Display version number. ``` ---------------------------------------- TITLE: Run Vite Preview Locally DESCRIPTION: Starts a local static web server to preview the production build. This command serves files from the `dist` directory, allowing you to test the application's appearance and functionality in a production-like environment. SOURCE: https://vite.dev/guide/static-deploy LANGUAGE: bash CODE: ``` $ npm run preview ``` ---------------------------------------- TITLE: Vite CSS Pre-processor Installation DESCRIPTION: Provides the necessary npm commands to install supported CSS pre-processors for use with Vite. Vite includes built-in support for Sass, Less, and Stylus. SOURCE: https://vite.dev/guide/features LANGUAGE: bash CODE: ``` # .scss and .sass npm add -D sass-embedded # or sass # .less npm add -D less # .styl and .stylus npm add -D stylus ``` ---------------------------------------- TITLE: Improve Server Cold Starts DESCRIPTION: Switch to a new strategy for dependency optimization that may help in large projects by holding off optimization until crawling is complete. This can be beneficial for projects experiencing slow server cold starts. SOURCE: https://vite.dev/blog/announcing-vite5-1 LANGUAGE: javascript CODE: ``` vite.config.js export default { optimizeDeps: { holdUntilCrawlEnd: false } } ``` ---------------------------------------- TITLE: Vercel CLI Deployment DESCRIPTION: Installs the Vercel CLI, initializes a Vite project, and provides commands to deploy the application. Vercel automatically detects Vite and configures settings. SOURCE: https://vite.dev/guide/static-deploy LANGUAGE: bash CODE: ``` $ npm i -g vercel $ vercel init vite Vercel CLI > Success! Initialized "vite" example in ~/your-folder. - To deploy, `cd vite` and run `vercel`. ``` ---------------------------------------- TITLE: Install Vite CLI with Package Managers DESCRIPTION: Installs the Vite CLI as a development dependency using different package managers like npm, yarn, pnpm, bun, and deno. SOURCE: https://vite.dev/guide LANGUAGE: bash CODE: ``` $ npm install -D vite ``` LANGUAGE: bash CODE: ``` $ yarn add -D vite ``` LANGUAGE: bash CODE: ``` $ pnpm add -D vite ``` LANGUAGE: bash CODE: ``` $ bun add -D vite ``` LANGUAGE: bash CODE: ``` $ deno add -D npm:vite ``` ---------------------------------------- TITLE: Custom Logger Example (TypeScript) DESCRIPTION: Demonstrates how to create and customize a Vite logger. This example shows how to use `createLogger` to get the default logger and then override its `warn` method to filter out specific warnings, such as empty CSS files. SOURCE: https://vite.dev/config/shared-options LANGUAGE: ts CODE: ``` import { createLogger, defineConfig } from 'vite' const logger = createLogger() const loggerWarn = logger.warn logger.warn = (msg, options) => { // Ignore empty CSS files warning if (msg.includes('vite:css') && msg.includes(' is empty')) return loggerWarn(msg, options) } export default defineConfig({ customLogger: logger, }) ``` ---------------------------------------- TITLE: Vite Default npm Scripts DESCRIPTION: Defines the standard npm scripts for common Vite operations: starting the dev server, building for production, and previewing the production build. SOURCE: https://vite.dev/guide LANGUAGE: json CODE: ``` { "scripts": { "dev": "vite", // start dev server, aliases: `vite dev`, `vite serve` "build": "vite build", // build for production "preview": "vite preview" // locally preview production build } } ``` ---------------------------------------- TITLE: Vite Server Middleware Mode Example DESCRIPTION: Demonstrates how to create a Vite development server in middleware mode, integrating it with an Express.js application. This allows Vite to handle requests within a custom server setup. SOURCE: https://vite.dev/config/server-options LANGUAGE: js CODE: ``` import express from 'express' import { createServer as createViteServer } from 'vite' async function createServer() { const app = express() // Create Vite server in middleware mode const vite = await createViteServer({ server: { middlewareMode: true }, // don't include Vite's default HTML handling middlewares appType: 'custom' }) // Use vite's connect instance as middleware app.use(vite.middlewares) app.use('*', async (req, res) => { // Since `appType` is `'custom'`, should serve response here. // Note: if `appType` is `'spa'` or `'mpa'`, Vite includes middlewares // to handle HTML requests and 404s so user middlewares should be added // before Vite's middlewares to take effect instead }) } createServer() ``` ---------------------------------------- TITLE: Custom Environment Instance Configuration DESCRIPTION: Example of configuring a custom 'ssr' environment using a provider, specifying a distinct output directory for the build process. SOURCE: https://vite.dev/guide/api-environment LANGUAGE: js CODE: ``` import { customEnvironment } from 'vite-environment-provider' export default { build: { outDir: '/dist/client', }, environments: { ssr: customEnvironment({ build: { outDir: '/dist/ssr', }, }), }, } ``` ---------------------------------------- TITLE: Install Terser for Minification DESCRIPTION: Installs Terser as a development dependency using npm. This is required when the `build.minify` option in Vite is set to `'terser'`. SOURCE: https://vite.dev/config/build-options LANGUAGE: sh CODE: ``` npm add -D terser ``` ---------------------------------------- TITLE: Install Trusted Certificate on macOS DESCRIPTION: Resolves network request issues in Chrome when using self-signed SSL certificates by installing a trusted certificate. This command adds a certificate to the login keychain. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: shell CODE: ``` security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain-db your-cert.cer ``` ---------------------------------------- TITLE: Vite 4.3 Performance Benchmarks (Babel) DESCRIPTION: Benchmark results comparing Vite 4.2 and Vite 4.3 with Babel for development server startup and HMR times. Includes metrics for dev cold start, dev warm start, root HMR, and leaf HMR. SOURCE: https://vite.dev/blog/announcing-vite4-3 LANGUAGE: markdown CODE: ``` | **Vite (babel)** | Vite 4.2 | Vite 4.3 | Improvement | | --- | --- | --- | --- | | **dev cold start** | 17249.0ms | 5132.4ms | -70.2% | | **dev warm start** | 6027.8ms | 4536.1ms | -24.7% | | **Root HMR** | 46.8ms | 26.7ms | -42.9% | | **Leaf HMR** | 27.0ms | 12.9ms | -52.2% | ``` ---------------------------------------- TITLE: Vite 3.0 Quick Links DESCRIPTION: Essential links for users transitioning to or learning about Vite 3.0, including access to the main documentation, migration guide, and detailed changelog. SOURCE: https://vite.dev/blog/announcing-vite3 LANGUAGE: APIDOC CODE: ``` Vite 3.0 Resources: - Docs: / - Migration Guide: https://v3.vite.dev/guide/migration - Changelog (v3.0.0): https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md#300-2022-07-13 ``` ---------------------------------------- TITLE: Vite: Preview Server Function DESCRIPTION: Starts a Vite preview server. It takes an optional inline configuration object and returns a promise that resolves to a PreviewServer instance. The server can be used to print URLs, bind CLI shortcuts, and access underlying server components. SOURCE: https://vite.dev/guide/api-javascript LANGUAGE: APIDOC CODE: ``` preview(inlineConfig?: InlineConfig): Promise<PreviewServer> - Starts a Vite preview server. - Parameters: - inlineConfig: Optional configuration object for the preview server. - Returns: - A Promise resolving to a PreviewServer instance. ``` LANGUAGE: ts CODE: ``` import { preview } from 'vite' const previewServer = await preview({ // any valid user config options, plus `mode` and `configFile` preview: { port: 8080, open: true, }, }) previewServer.printUrls() previewServer.bindCLIShortcuts({ print: true }) ``` ---------------------------------------- TITLE: ViteDevServer.listen Method Signature DESCRIPTION: Provides the TypeScript signature for the `listen` method of the ViteDevServer, detailing its parameters and return type for starting the development server. SOURCE: https://vite.dev/index LANGUAGE: APIDOC CODE: ``` ViteDevServer.listen(port?: number | undefined, isRestart?: boolean | undefined): Promise<ViteDevServer> - Starts the server. - Parameters: - port: Optional port number to listen on. - isRestart: Optional boolean indicating if this is a server restart. - Returns: A Promise that resolves to the ViteDevServer instance. ``` ---------------------------------------- TITLE: Vite 4.3 Performance Benchmarks (SWC) DESCRIPTION: Benchmark results comparing Vite 4.2 and Vite 4.3 with SWC for development server startup and HMR times. Includes metrics for dev cold start, dev warm start, root HMR, and leaf HMR. SOURCE: https://vite.dev/blog/announcing-vite4-3 LANGUAGE: markdown CODE: ``` | **Vite (swc)** | Vite 4.2 | Vite 4.3 | Improvement | | --- | --- | --- | --- | | **dev cold start** | 13552.5ms | 3201.0ms | -76.4% | | **dev warm start** | 4625.5ms | 2834.4ms | -38.7% | | **Root HMR** | 30.5ms | 24.0ms | -21.3% | | **Leaf HMR** | 16.9ms | 10.0ms | -40.8% | ``` ---------------------------------------- TITLE: Vite Server FS Allow Example DESCRIPTION: Configures Vite's file system access control, allowing specific directories or files to be served via the /@fs/ URL. This example shows how to allow files one level above the project root. SOURCE: https://vite.dev/config/server-options LANGUAGE: js CODE: ``` export default defineConfig({ server: { fs: { // Allow serving files from one level up to the project root allow: ['..'] } } }) ``` ---------------------------------------- TITLE: Scaffold Vite Project with pnpm DESCRIPTION: Command to create a new Vite project using pnpm. It allows scaffolding with various frameworks and runtimes, providing a quick start for development. SOURCE: https://vite.dev/blog/announcing-vite4 LANGUAGE: bash CODE: ``` pnpm create vite ``` ---------------------------------------- TITLE: Play Vite Online DESCRIPTION: Provides a quick way to experiment with Vite 6 in an online environment without local setup. This is useful for testing and exploring Vite's capabilities. SOURCE: https://vite.dev/blog/announcing-vite6 LANGUAGE: url CODE: ``` vite.new ``` ---------------------------------------- TITLE: Worker Thread Transport Implementation DESCRIPTION: Example of implementing ModuleRunnerTransport for communication with a worker thread using Node.js's parentPort. This setup is used when the module runner operates in a separate worker context. SOURCE: https://vite.dev/guide/api-environment-runtimes LANGUAGE: js CODE: ``` import { parentPort } from 'node:worker_threads' import { fileURLToPath } from 'node:url' import { ESModulesEvaluator, ModuleRunner } from 'vite/module-runner' /** @type {import('vite/module-runner').ModuleRunnerTransport} */ const transport = { connect({ onMessage, onDisconnection }) { parentPort.on('message', onMessage) parentPort.on('close', onDisconnection) }, send(data) { parentPort.postMessage(data) }, } const runner = new ModuleRunner( { transport, }, new ESModulesEvaluator(), ) await runner.import('/entry.js') ``` ---------------------------------------- TITLE: Vite HotUpdate Hook: Full Reload Example DESCRIPTION: An example of using the `hotUpdate` hook to manually invalidate modules and trigger a full page reload by returning an empty array and sending a 'full-reload' event. SOURCE: https://vite.dev/guide/api-environment-plugins LANGUAGE: js CODE: ``` hotUpdate({ modules, timestamp }) { if (this.environment.name !== 'client') return // Invalidate modules manually const invalidatedModules = new Set() for (const mod of modules) { this.environment.moduleGraph.invalidateModule( mod, invalidatedModules, timestamp, true ) } this.environment.hot.send({ type: 'full-reload' }) return [] } ``` ---------------------------------------- TITLE: Scaffold Vite Project with pnpm create vite-extra DESCRIPTION: Command to create a new Vite project using pnpm, providing access to additional templates like Solid, Deno, SSR, and library starters. This offers more specialized project setups. SOURCE: https://vite.dev/blog/announcing-vite4 LANGUAGE: bash CODE: ``` pnpm create vite-extra ``` ---------------------------------------- TITLE: Vite's Production Transform Example DESCRIPTION: Illustrates how Vite transforms dynamic URL resolution during production builds. It maps a dynamic path to specific imported module assets, ensuring correct asset references. SOURCE: https://vite.dev/guide/assets LANGUAGE: javascript CODE: ``` import __img0png from './dir/img0.png' import __img1png from './dir/img1.png' function getImageUrl(name) { const modules = { './dir/img0.png': __img0png, './dir/img1.png': __img1png } return new URL(modules[`./dir/${name}.png`], import.meta.url).href } ``` ---------------------------------------- TITLE: Render Vite Assets in Production HTML (HTML) DESCRIPTION: Provides an example HTML template for rendering Vite assets in production. It demonstrates how to use the manifest file to link hashed CSS and JavaScript files. SOURCE: https://vite.dev/guide/backend-integration LANGUAGE: html CODE: ``` <!-- if production --> <!-- for cssFile of manifest[name].css --> <link rel="stylesheet" href="/{{ cssFile }}" /> <!-- for chunk of importedChunks(manifest, name) --> <!-- for cssFile of chunk.css --> <link rel="stylesheet" href="/{{ cssFile }}" /> <script type="module" src="/{{ manifest[name].file }}"></script> <!-- for chunk of importedChunks(manifest, name) --> <link rel="modulepreload" href="/{{ chunk.file }}" /> ``` ---------------------------------------- TITLE: Vite SSR Middleware Implementation DESCRIPTION: Provides a comprehensive example of setting up a Vite server in middleware mode and implementing an Express-like middleware to handle SSR requests. It covers reading the index.html, transforming it with Vite, importing the server entry point, rendering the application, and injecting the result into the HTML. SOURCE: https://vite.dev/guide/api-environment-frameworks LANGUAGE: js CODE: ``` import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import { createServer } from 'vite' const __dirname = path.dirname(fileURLToPath(import.meta.url)) const viteServer = await createServer({ server: { middlewareMode: true }, appType: 'custom', environments: { server: { // by default, modules are run in the same process as the vite server }, }, }) // You might need to cast this to RunnableDevEnvironment in TypeScript or // use isRunnableDevEnvironment to guard the access to the runner const serverEnvironment = viteServer.environments.server app.use('*', async (req, res, next) => { const url = req.originalUrl // 1. Read index.html const indexHtmlPath = path.resolve(__dirname, 'index.html') let template = fs.readFileSync(indexHtmlPath, 'utf-8') // 2. Apply Vite HTML transforms. This injects the Vite HMR client, // and also applies HTML transforms from Vite plugins, e.g. global // preambles from @vitejs/plugin-react template = await viteServer.transformIndexHtml(url, template) // 3. Load the server entry. import(url) automatically transforms // ESM source code to be usable in Node.js! There is no bundling // required, and provides full HMR support. const { render } = await serverEnvironment.runner.import( '/src/entry-server.js', ) // 4. render the app HTML. This assumes entry-server.js's exported // `render` function calls appropriate framework SSR APIs, // e.g. ReactDOMServer.renderToString() const appHtml = await render(url) // 5. Inject the app-rendered HTML into the template. const html = template.replace(`<!--ssr-outlet-->`, appHtml) // 6. Send the rendered HTML back. res.status(200).set({ 'Content-Type': 'text/html' }).end(html) }) ``` ---------------------------------------- TITLE: Vite Bare Module Import Example DESCRIPTION: Illustrates how Vite processes bare module imports, which are not natively supported by browsers. Vite rewrites these imports to valid URLs, enabling them to be resolved and served correctly, often after pre-bundling. SOURCE: https://vite.dev/guide/features LANGUAGE: javascript CODE: ``` import { someMethod } from 'my-dep' ``` ---------------------------------------- TITLE: Vite Debug Transform Logs DESCRIPTION: Example output from running Vite with the `--debug transform` flag. This helps identify files that take longer to transform, which can then be pre-warmed up by the development server. SOURCE: https://vite.dev/guide/performance LANGUAGE: bash CODE: ``` vite:transform 28.72ms /@vite/client +1ms vite:transform 62.95ms /src/components/BigComponent.vue +1ms vite:transform 102.54ms /src/utils/big-utils.js +1ms ``` ---------------------------------------- TITLE: Setup Vite Dev Server with Express Middleware (JS) DESCRIPTION: This snippet demonstrates initializing an Express server and integrating Vite's development server in middleware mode. It configures Vite to disable its own HTML serving, allowing the parent server to manage requests. This setup is crucial for SSR applications where the Node.js server handles rendering. SOURCE: https://vite.dev/guide/ssr LANGUAGE: js CODE: ``` import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import express from 'express' import { createServer as createViteServer } from 'vite' const __dirname = path.dirname(fileURLToPath(import.meta.url)) async function createServer() { const app = express() // Create Vite server in middleware mode and configure the app type as // 'custom', disabling Vite's own HTML serving logic so parent server // can take control const vite = await createViteServer({ server: { middlewareMode: true }, appType: 'custom' }) // Use vite's connect instance as middleware. If you use your own // express router (express.Router()), you should use router.use // When the server restarts (for example after the user modifies // vite.config.js), `vite.middlewares` is still going to be the same // reference (with a new internal stack of Vite and plugin-injected // middlewares). The following is valid even after restarts. app.use(vite.middlewares) app.use('*all', async (req, res) => { // serve index.html - we will tackle this next }) app.listen(5173) } createServer() ``` ---------------------------------------- TITLE: HTTP Request Transport Implementation DESCRIPTION: Example of implementing ModuleRunnerTransport using fetch for HTTP requests to communicate with a server. This is suitable for environments where direct process communication is not feasible. SOURCE: https://vite.dev/guide/api-environment-runtimes LANGUAGE: ts CODE: ``` import { ESModulesEvaluator, ModuleRunner } from 'vite/module-runner' export const runner = new ModuleRunner( { transport: { async invoke(data) { const response = await fetch(`http://my-vite-server/invoke`, { method: 'POST', body: JSON.stringify(data), }) return response.json() }, }, hmr: false, // disable HMR as HMR requires transport.connect }, new ESModulesEvaluator(), ) await runner.import('/entry.js') ``` ---------------------------------------- TITLE: GitHub Pages Deployment Workflow DESCRIPTION: A GitHub Actions workflow to automate the deployment of static content to GitHub Pages. It checks out code, sets up Node.js, installs dependencies, builds the project, configures pages, uploads the build artifact, and deploys. SOURCE: https://vite.dev/guide/static-deploy LANGUAGE: yaml CODE: ``` # Simple workflow for deploying static content to GitHub Pages name: Deploy static content to Pages on: # Runs on pushes targeting the default branch push: branches: ['main'] # Allows you to run this workflow manually from the Actions tab workflow_dispatch: # Sets the GITHUB_TOKEN permissions to allow deployment to GitHub Pages permissions: contents: read pages: write id-token: write # Allow one concurrent deployment concurrency: group: 'pages' cancel-in-progress: true jobs: # Single deploy job since we're just deploying deploy: environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Set up Node uses: actions/setup-node@v4 with: node-version: lts/* cache: 'npm' - name: Install dependencies run: npm ci - name: Build run: npm run build - name: Setup Pages uses: actions/configure-pages@v5 - name: Upload artifact uses: actions/upload-pages-artifact@v3 with: # Upload dist folder path: './dist' - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v4 ``` ---------------------------------------- TITLE: Vite Config: Optimize Dependencies DESCRIPTION: Configuration example for Vite's dependency optimization in `vite.config.js`. It demonstrates how to use `optimizeDeps.include` and `build.commonjsOptions.include` to manage linked dependencies in monorepos and ensure proper bundling of CommonJS modules. SOURCE: https://vite.dev/guide/dep-pre-bundling LANGUAGE: js CODE: ``` export default defineConfig({ optimizeDeps: { include: ['linked-dep'], }, build: { commonjsOptions: { include: [/linked-dep/, /node_modules/], }, }, }) ``` ---------------------------------------- TITLE: Server-Side HTTP Invoke Handler DESCRIPTION: Example of how a server can handle incoming HTTP requests for the 'invoke' operation from a ModuleRunnerTransport. This demonstrates processing the payload and returning the result or error. SOURCE: https://vite.dev/guide/api-environment-runtimes LANGUAGE: ts CODE: ``` const customEnvironment = new DevEnvironment(name, config, context) server.onRequest((request: Request) => { const url = new URL(request.url) if (url.pathname === '/invoke') { const payload = (await request.json()) as HotPayload const result = customEnvironment.hot.handleInvoke(payload) return new Response(JSON.stringify(result)) } return Response.error() }) ``` ---------------------------------------- TITLE: Cloudflare Pages Deployment via Wrangler DESCRIPTION: Steps to deploy a Vite application to Cloudflare Pages using the Wrangler CLI. This involves installing Wrangler, logging in, building the project, and deploying the 'dist' directory. SOURCE: https://vite.dev/guide/static-deploy LANGUAGE: bash CODE: ``` # Install Wrangler CLI $ npm install -g wrangler # Login to Cloudflare account from CLI $ wrangler login # Run your build command $ npm run build # Create new deployment $ npx wrangler pages deploy dist ``` ---------------------------------------- TITLE: Vite Version Documentation Links DESCRIPTION: Provides direct links to the documentation for various major versions of Vite, allowing users to access specific version guides and features. SOURCE: https://vite.dev/blog/announcing-vite3 LANGUAGE: APIDOC CODE: ``` Vite Version Docs: - Vite 6 Docs: https://v6.vite.dev - Vite 5 Docs: https://v5.vite.dev - Vite 4 Docs: https://v4.vite.dev - Vite 3 Docs: https://v3.vite.dev - Vite 2 Docs: https://v2.vite.dev ``` ---------------------------------------- TITLE: Create Vite Dev Server with Basic Configuration DESCRIPTION: Demonstrates how to programmatically create a Vite development server using `createServer`. It shows setting the root directory, port, and binding CLI shortcuts. SOURCE: https://vite.dev/guide/api-javascript LANGUAGE: ts CODE: ``` import { fileURLToPath } from 'node:url' import { createServer } from 'vite' const __dirname = fileURLToPath(new URL('.', import.meta.url)) const server = await createServer({ // any valid user config options, plus `mode` and `configFile` configFile: false, root: __dirname, server: { port: 1337 } }) await server.listen() server.printUrls() server.bindCLIShortcuts({ print: true }) ``` ---------------------------------------- TITLE: GitLab CI for GitLab Pages DESCRIPTION: A GitLab CI configuration file to build and deploy a Vite application to GitLab Pages. It uses a Node.js Docker image, installs dependencies, builds the project, and copies the output to the public directory for GitLab Pages. SOURCE: https://vite.dev/guide/static-deploy LANGUAGE: yaml CODE: ``` image: node:lts pages: stage: deploy cache: key: files: - package-lock.json prefix: npm paths: - node_modules/ script: - npm install - npm run build - cp -a dist/. public/ artifacts: paths: - public rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH ``` ---------------------------------------- TITLE: Vite Plugin Authoring Guide DESCRIPTION: Guidance on creating Vite plugins, emphasizing extension of Rollup's plugin interface and Vite-specific options. It suggests checking existing features and community plugins before authoring, and provides tips for inlining plugins in vite.config.js and using vite-plugin-inspect for debugging. SOURCE: https://vite.dev/guide/api-plugin LANGUAGE: APIDOC CODE: ``` Plugin API Overview: Extends Rollup's plugin interface with Vite-specific options. Works for both development and build. Authoring a Plugin: - Check Vite Features guide first. - Review community plugins (Rollup compatible and Vite specific). - Can be inlined in vite.config.js. - Consider sharing useful plugins. Debugging Tip: - Use vite-plugin-inspect for intermediate state inspection. - Install: npm install vite-plugin-inspect --save-dev - Visit: localhost:5173/__inspect/ to inspect modules and transformation stack. Configuration Example (Conceptual): // vite.config.js import myPlugin from './my-vite-plugin'; export default { plugins: [ myPlugin({ // plugin options }), // other plugins... ] } ``` ---------------------------------------- TITLE: Vite Configuration Options DESCRIPTION: Configuration options for Vite's development server. `server.warmup` pre-transforms modules for faster startup, and `server.open` automatically opens the app in the browser. SOURCE: https://vite.dev/blog/announcing-vite5 LANGUAGE: APIDOC CODE: ``` server.warmup: object | object[] Description: Define a list of modules that should be pre-transformed as soon as the server starts to improve startup time. Example: server: { warmup: [ '/src/main.js', '/src/components/MyComponent.vue' ] } server.open: boolean | string Description: Automatically open the app in the browser when the dev server starts. If true, Vite will open the default entry point. If a string, Vite will open the provided URL. Default: false Example: server: { open: true } server: { open: '/dashboard' } ``` ---------------------------------------- TITLE: Handling ESM-Only Packages in Vite Config DESCRIPTION: Explains how to resolve issues when importing ESM-only packages using `require` in Vite's configuration file. It provides recommended solutions for compatibility. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: APIDOC CODE: ``` Error: Failed to resolve "foo". This package is ESM only but it was tried to load by `require`. Error [ERR_REQUIRE_ESM]: require() of ES Module /path/to/dependency.js from /path/to/vite.config.js not supported. Instead change the require of index.js in /path/to/vite.config.js to a dynamic import() which is available in all CommonJS modules. Description: This error arises when attempting to load an ECMAScript Module (ESM) only package using Node.js's `require` function, which is not supported by default in older Node.js versions (<=22) when loading ESM. Dynamic import() is the recommended approach. Resolution: Convert your Vite configuration file to use ESM: 1. Add `"type": "module"` to the nearest `package.json` file. OR 2. Rename your configuration file from `vite.config.js` or `vite.config.ts` to `vite.config.mjs` or `vite.config.mts` respectively. ``` ---------------------------------------- TITLE: Migration to Vite 6 DESCRIPTION: Guidance for updating projects to Vite 6, advising a review of the detailed Migration Guide for a straightforward update process. The complete list of changes is available in the official Vite 6 Changelog. SOURCE: https://vite.dev/blog/announcing-vite6 LANGUAGE: APIDOC CODE: ``` Migrating to Vite 6: Process: Generally straightforward for most projects. Recommendation: Review the detailed Migration Guide before upgrading. Resources: - Detailed Migration Guide: /guide/migration - Vite 6 Changelog: https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md#500-2024-11-26 ``` ---------------------------------------- TITLE: Create Vite Virtual Module Plugin (JavaScript) DESCRIPTION: Example of a Vite plugin that implements the virtual module convention. It defines how to resolve and load custom modules during the build process, enabling build-time information injection into source files. SOURCE: https://vite.dev/guide/api-plugin LANGUAGE: javascript CODE: ``` export default function myPlugin() { const virtualModuleId = 'virtual:my-module' const resolvedVirtualModuleId = '\0' + virtualModuleId return { name: 'my-plugin', // required, will show up in warnings and errors resolveId(id) { if (id === virtualModuleId) { return resolvedVirtualModuleId } }, load(id) { if (id === resolvedVirtualModuleId) { return `export const msg = "from virtual module"` } }, } } ``` ---------------------------------------- TITLE: Build for Production with Vite CLI DESCRIPTION: Run the `vite build` command to create an optimized production bundle for your Vite application. By default, it uses `<root>/index.html` as the entry point and generates static assets suitable for hosting. SOURCE: https://vite.dev/guide/build LANGUAGE: CLI CODE: ``` vite build ``` ---------------------------------------- TITLE: Vite CLI Path Error on Windows DESCRIPTION: Addresses an error where Vite cannot find its module on Windows due to special characters like '&' in the project path. It suggests workarounds to resolve this issue. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: APIDOC CODE: ``` Error: Cannot find module 'C:\\foo\\bar&baz\\vite\\bin\\vite.js' Description: This error occurs on Windows when the project folder path contains special characters, specifically '&', which is not handled correctly by npm's cmd-shim. Resolution: 1. Switch to an alternative package manager like `pnpm` or `yarn`. 2. Remove the special character '&' from the project directory path. ``` ---------------------------------------- TITLE: Self-Accepting Module Invalidation Example DESCRIPTION: Demonstrates how a self-accepting module can detect it cannot handle an HMR update and then invalidate itself, propagating the update requirement to its importers. SOURCE: https://vite.dev/guide/api-hmr LANGUAGE: javascript CODE: ``` import.meta.hot.accept((module) => { // You may use the new module instance to decide whether to invalidate. if (cannotHandleUpdate(module)) { import.meta.hot.invalidate() } }) ``` ---------------------------------------- TITLE: Scaffold Vite Project DESCRIPTION: Use the Vite CLI to quickly create new projects with your preferred framework. Supports various templates including framework-specific starters and additional options via `vite-extra`. SOURCE: https://vite.dev/blog/announcing-vite5 LANGUAGE: bash CODE: ``` pnpm create vite pnpm create vite-extra ``` ---------------------------------------- TITLE: Profile Vite Build Performance DESCRIPTION: To diagnose performance bottlenecks during the Vite build process, you can enable the Node.js inspector. This allows you to generate a CPU profile for analysis. Use the `--profile` flag with the `vite build` command. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: bash CODE: ``` vite build --profile ``` ---------------------------------------- TITLE: Windows subst command for virtual drives DESCRIPTION: The `subst` command in Windows creates a virtual drive linked to a folder. If your project resides on such a virtual drive, Vite may encounter issues. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: shell CODE: ``` subst <driveletter>: <path> Example: subst Z: C:\MyProject\Frontend ``` ---------------------------------------- TITLE: Vite Server Origin Example DESCRIPTION: Sets a custom origin for asset URLs generated by Vite during development. This is useful for scenarios where the development server runs on a different origin than the final deployment. SOURCE: https://vite.dev/config/server-options LANGUAGE: js CODE: ``` export default defineConfig({ server: { origin: 'http://127.0.0.1:8080' } }) ``` ---------------------------------------- TITLE: Vite Plugin: Load and Transform Index.html via Virtual Module DESCRIPTION: Provides an example of a Vite plugin that resolves and loads a virtual module for `index.html`. It demonstrates reading the HTML file, transforming it using Vite's `transformIndexHtml` API, and exporting the content, including watching the source file. SOURCE: https://vite.dev/guide/api-environment-frameworks LANGUAGE: ts CODE: ``` import fs from 'fs' import { Plugin, ViteDevServer } from 'vite' function vitePluginVirtualIndexHtml(): Plugin { let server: ViteDevServer | undefined return { name: vitePluginVirtualIndexHtml.name, configureServer(server_) { server = server_ }, resolveId(source) { return source === 'virtual:index-html' ? '\0' + source : undefined }, async load(id) { if (id === '\0' + 'virtual:index-html') { let html: string if (server) { this.addWatchFile('index.html') html = fs.readFileSync('index.html', 'utf-8') html = await server.transformIndexHtml('/', html) } else { html = fs.readFileSync('dist/client/index.html', 'utf-8') } return `export default ${JSON.stringify(html)}` } return }, } } ``` ---------------------------------------- TITLE: Create Vite Extra Templates DESCRIPTION: Accesses additional Vite starter templates for various frameworks and runtimes, including Solid, Deno, SSR, and library starters. This command is also accessible via the 'Others' option in `create vite`. SOURCE: https://vite.dev/blog/announcing-vite6 LANGUAGE: bash CODE: ``` pnpm create vite-extra ``` ---------------------------------------- TITLE: Increase Linux File Descriptor Limits DESCRIPTION: Addresses issues where requests stall on Linux due to file descriptor limits. Provides commands to temporarily increase limits for file descriptors and inotify, and suggests configuration file modifications for persistence. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: shell CODE: ``` # Check current limit $ ulimit -Sn # Change limit (temporary) $ ulimit -Sn 10000 # You might need to change the hard limit too # Restart your browser # Check current limits $ sysctl fs.inotify # Change limits (temporary) $ sudo sysctl fs.inotify.max_queued_events=16384 $ sudo sysctl fs.inotify.max_user_instances=8192 $ sudo sysctl fs.inotify.max_user_watches=524288 # For persistent changes, uncomment and add to systemd config files: # /etc/systemd/system.conf # /etc/systemd/user.conf # DefaultLimitNOFILE=65536 # For Ubuntu Linux, alternatively edit /etc/security/limits.conf: # * - nofile 65536 # Note: A restart is required for persistent changes. ``` ---------------------------------------- TITLE: Profile Vite Dev Server Performance DESCRIPTION: To diagnose performance bottlenecks in the Vite development server, you can enable the Node.js inspector. This allows you to generate a CPU profile for analysis. Use the `--profile` flag with the `vite` command and `--open` to automatically launch the application. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: bash CODE: ``` vite --profile --open ``` ---------------------------------------- TITLE: React Support with @vitejs/plugin-react-swc DESCRIPTION: Replaces Babel with SWC for faster development builds, especially for large projects. It uses SWC and esbuild during production builds, significantly improving cold start and HMR performance. SOURCE: https://vite.dev/plugins LANGUAGE: javascript CODE: ``` import reactSwc from '@vitejs/plugin-react-swc' export default { plugins: [ reactSwc() ] } ``` ---------------------------------------- TITLE: Vite Client-Side Custom HMR Handler DESCRIPTION: Example of client-side JavaScript code that listens for custom HMR events sent from the server (e.g., 'special-update') and executes custom update logic. SOURCE: https://vite.dev/guide/api-environment-plugins LANGUAGE: js CODE: ``` if (import.meta.hot) { import.meta.hot.on('special-update', (data) => { // perform custom update }) } ``` ---------------------------------------- TITLE: Vite File Change Detection (WSL2) DESCRIPTION: Explains potential issues with Vite not detecting file changes when running on WSL2. It suggests configuring the `server.watch` option to ensure file changes are monitored correctly. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: config CODE: ``` # vite.config.js or vite.config.ts import { defineConfig } from 'vite' export default defineConfig({ server: { watch: { // Options to configure file watching // e.g., usePolling: true if file system events are not reliable } } }) ``` ---------------------------------------- TITLE: Windows mklink command for symlinks/junctions DESCRIPTION: The `mklink` command in Windows creates symbolic links or directory junctions. Using `mklink` to link to a different drive, such as for a Yarn global cache, can cause Vite to fail. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: shell CODE: ``` mklink [/D | /H | /J] <Link> <Target> Example for a directory junction: mklink /J C:\Users\User\.yarn C:\Users\User\AppData\Local\Yarn\global ``` ---------------------------------------- TITLE: Configure Preview Server Hook in Vite DESCRIPTION: The configurePreviewServer hook allows customization of the Vite preview server. It is called before other middlewares are installed. Returning a function from this hook enables injecting middleware after internal middlewares are set up, providing a post-setup hook. SOURCE: https://vite.dev/guide/api-plugin LANGUAGE: js CODE: ``` const myPlugin = () => ({ name: 'configure-preview-server', configurePreviewServer(server) { // return a post hook that is called after other middlewares are // installed return () => { server.middlewares.use((req, res, next) => { // custom handle request... }) } }, }) ``` ---------------------------------------- TITLE: Vite API Migration: Server to Environment Instances DESCRIPTION: Guides Vite plugin authors on migrating from deprecated ViteDevServer methods to their new locations within DevEnvironment instances. This change is crucial for compatibility with Vite v6 and beyond. SOURCE: https://vite.dev/changes/per-environment-apis LANGUAGE: APIDOC CODE: ``` Vite API Migration Guide: This section outlines the migration path for Vite plugin authors from deprecated `ViteDevServer` methods to the new `DevEnvironment` instances, introduced in Vite v6. **Motivation:** In Vite v5 and earlier, a single Vite dev server managed both `client` and `ssr` environments. APIs like `server.moduleGraph` and `server.transformRequest` handled modules from both, often requiring an `ssr` boolean parameter. Vite v6 allows for multiple custom environments (e.g., `client`, `ssr`, `edge`). To accommodate this, methods have been moved to the respective `environment` instances, simplifying their usage and removing the need for an `ssr` flag. **Affected Scope:** Vite Plugin Authors **Future Deprecation:** Deprecation of `server.moduleGraph` and other methods now located in environments is planned for a future major release. It is not recommended to move away from server methods immediately, but identifying usage is advised. **Migration Steps:** * **Module Graph Access:** - **Old:** `server.moduleGraph` - **New:** `environment.moduleGraph` - **Reference:** [/guide/api-environment-instances#separate-module-graphs](/guide/api-environment-instances#separate-module-graphs) * **Transform Request:** - **Old:** `server.transformRequest(url, { ssr })` - **New:** `environment.transformRequest(url)` * **Warmup Request:** - **Old:** `server.warmupRequest(url, { ssr })` - **New:** `environment.warmupRequest(url)` **Example of API Usage Change:** ```javascript // Before Vite v6 async function handleRequest(server, url, ssr) { const module = await server.moduleGraph.getModuleByUrl(url, ssr); const transformed = await server.transformRequest(url, { ssr }); await server.warmupRequest(url, { ssr }); // ... } // After Vite v6 (using a specific environment instance) async function handleRequest(environment, url) { const module = await environment.moduleGraph.getModuleByUrl(url); const transformed = await environment.transformRequest(url); await environment.warmupRequest(url); // ... } ``` **Related Methods/Concepts:** - `DevEnvironment` instances: Allow creation of custom environments beyond `client` and `ssr`. - `server.moduleGraph`: Previously held modules from all environments, now separated per `DevEnvironment`. - `server.transformRequest`: Previously required an `ssr` option, now context-aware within the `environment`. ``` ---------------------------------------- TITLE: Create Workerd Development Environment DESCRIPTION: Provides an example of a TypeScript function `createWorkerdDevEnvironment` that instantiates Vite's `DevEnvironment`. It sets up custom resolve conditions and a `HotChannel` for communication, enabling hot module replacement for the Workerd runtime. SOURCE: https://vite.dev/guide/api-environment-runtimes LANGUAGE: ts CODE: ``` import { DevEnvironment, HotChannel } from 'vite' function createWorkerdDevEnvironment( name: string, config: ResolvedConfig, context: DevEnvironmentContext ) { const connection = /* ... */ const transport: HotChannel = { on: (listener) => { connection.on('message', listener) }, send: (data) => connection.send(data), } const workerdDevEnvironment = new DevEnvironment(name, config, { options: { resolve: { conditions: ['custom'] }, ...context.options, }, hot: true, transport, }) return workerdDevEnvironment } ``` ---------------------------------------- TITLE: Scaffold Vite Project (Basic) DESCRIPTION: Commands to create a new Vite project using different package managers. These commands initiate the project scaffolding process, prompting the user for project name and framework selection. SOURCE: https://vite.dev/guide LANGUAGE: bash CODE: ``` $ npm create vite@latest ``` LANGUAGE: bash CODE: ``` $ yarn create vite ``` LANGUAGE: bash CODE: ``` $ pnpm create vite ``` LANGUAGE: bash CODE: ``` $ bun create vite ``` LANGUAGE: bash CODE: ``` $ deno init --npm vite ``` ---------------------------------------- TITLE: Basic Vite HTML Entry Point DESCRIPTION: A minimal HTML file that serves as the entry point for a Vite project during development. SOURCE: https://vite.dev/guide LANGUAGE: html CODE: ``` <p>Hello Vite!</p> ``` ---------------------------------------- TITLE: Vite Server HTTPS Configuration DESCRIPTION: Enables TLS + HTTP/2 for the development server. Accepts an options object compatible with Node.js's `https.createServer()`. A basic setup can use `@vitejs/plugin-basic-ssl`, but custom certificates are recommended. SOURCE: https://vite.dev/config/server-options LANGUAGE: APIDOC CODE: ``` server.https Type: https.ServerOptions Description: Enable TLS + HTTP/2. The value is an options object passed to `https.createServer()`. Note that this downgrades to TLS only when the `server.proxy` option is also used. A valid certificate is needed. For a basic setup, you can add `@vitejs/plugin-basic-ssl` to the project plugins, which will automatically create and cache a self-signed certificate. But we recommend creating your own certificates. ``` ---------------------------------------- TITLE: Vite Server Auto Open Configuration DESCRIPTION: Configures automatic browser opening upon server start. Can be a boolean to open the default URL or a string to specify a pathname. Environment variables `process.env.BROWSER` and `process.env.BROWSER_ARGS` can customize the browser and arguments. SOURCE: https://vite.dev/config/server-options LANGUAGE: javascript CODE: ``` export default defineConfig({ server: { open: '/docs/index.html', }, }) ``` LANGUAGE: APIDOC CODE: ``` server.open Type: boolean | string Description: Automatically open the app in the browser on server start. When the value is a string, it will be used as the URL's pathname. If you want to open the server in a specific browser you like, you can set the env `process.env.BROWSER` (e.g. `firefox`). You can also set `process.env.BROWSER_ARGS` to pass additional arguments (e.g. `--incognito`). `BROWSER` and `BROWSER_ARGS` are also special environment variables you can set in the `.env` file to configure it. See the `open` package for more details. ``` ---------------------------------------- TITLE: Vite: Configure server.sourcemapIgnoreList DESCRIPTION: Example of configuring the `server.sourcemapIgnoreList` option in Vite. This function determines which source files should be ignored in the server's sourcemap, defaulting to ignoring files within `node_modules`. SOURCE: https://vite.dev/config/server-options LANGUAGE: js CODE: ``` import { defineConfig } from 'vite'; export default defineConfig({ server: { // This is the default value, and will add all files with node_modules // in their paths to the ignore list. sourcemapIgnoreList(sourcePath, sourcemapPath) { return sourcePath.includes('node_modules'); }, }, }); ``` ---------------------------------------- TITLE: Vite Configuration: Terser Minification DESCRIPTION: Configuration option to enable Terser as the minifier for JavaScript and CSS builds in Vite. If this option is used, the 'terser' package must be installed as a development dependency. SOURCE: https://vite.dev/blog/announcing-vite3 LANGUAGE: JavaScript CODE: ``` build: { minify: 'terser' } ``` LANGUAGE: Shell CODE: ``` npm add -D terser ``` ---------------------------------------- TITLE: Transform Custom File Types DESCRIPTION: Provides an example of a Vite/Rollup plugin factory function designed to transform custom file extensions. It uses the `transform` hook to compile files with a specific extension into JavaScript. SOURCE: https://vite.dev/guide/api-plugin LANGUAGE: js CODE: ``` const fileRegex = /\.(my-file-ext)$/ export default function myPlugin() { return { name: 'transform-file', transform(src, id) { if (fileRegex.test(id)) { return { code: compileFileToJS(src), map: null, // provide source map if available } } }, } } ``` ---------------------------------------- TITLE: Add Legacy Browser Support Plugin in Vite DESCRIPTION: Demonstrates how to add the official @vitejs/plugin-legacy to a Vite project to support older browsers. This involves installing the plugin as a dev dependency and configuring it within vite.config.js to specify target browser versions. SOURCE: https://vite.dev/guide/using-plugins LANGUAGE: shell CODE: ``` npm add -D @vitejs/plugin-legacy ``` LANGUAGE: js CODE: ``` import legacy from '@vitejs/plugin-legacy' import { defineConfig } from 'vite' export default defineConfig({ plugins: [ legacy({ targets: ['defaults', 'not IE 11'], }), ], }) ``` ---------------------------------------- TITLE: Vite Glob Import Named Imports DESCRIPTION: Explains how to import specific exports from modules using the `import` option in `import.meta.glob`. This allows targeting named exports (e.g., `setup`) or the default export, improving tree-shaking and reducing bundle size when only specific parts of modules are needed. SOURCE: https://vite.dev/guide/features LANGUAGE: ts CODE: ``` const modules = import.meta.glob('./dir/*.js', { import: 'setup' }) ``` LANGUAGE: ts CODE: ``` // code produced by vite const modules = { './dir/bar.js': () => import('./dir/bar.js').then((m) => m.setup), './dir/foo.js': () => import('./dir/foo.js').then((m) => m.setup), } ``` LANGUAGE: ts CODE: ``` const modules = import.meta.glob('./dir/*.js', { import: 'setup', eager: true, }) ``` LANGUAGE: ts CODE: ``` // code produced by vite: import { setup as __vite_glob_0_0 } from './dir/bar.js' import { setup as __vite_glob_0_1 } from './dir/foo.js' const modules = { './dir/bar.js': __vite_glob_0_0, './dir/foo.js': __vite_glob_0_1, } ``` LANGUAGE: ts CODE: ``` const modules = import.meta.glob('./dir/*.js', { import: 'default', eager: true, }) ``` LANGUAGE: ts CODE: ``` // code produced by vite: import { default as __vite_glob_0_0 } from './dir/bar.js' import { default as __vite_glob_0_1 } from './dir/foo.js' const modules = { './dir/bar.js': __vite_glob_0_0, './dir/foo.js': __vite_glob_0_1, } ``` ---------------------------------------- TITLE: Profile Vite Dev Server Startup DESCRIPTION: Use the `vite --profile` command to generate a CPU profile of the Vite development server startup. This profile can be analyzed with tools like speedscope to identify performance bottlenecks. Press 'p' after the page loads to trigger the profile saving. SOURCE: https://vite.dev/blog/announcing-vite4-3 LANGUAGE: bash CODE: ``` vite --profile ``` ---------------------------------------- TITLE: HMR Full Reload Troubleshooting DESCRIPTION: Explains why a full reload might occur instead of HMR. This happens when HMR is not handled by Vite or a plugin, or if a circular dependency is detected, requiring a reload to maintain execution order. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: shell CODE: ``` # To diagnose circular dependencies triggering full reloads: vite --debug hmr ``` ---------------------------------------- TITLE: Vite Core APIs Overview DESCRIPTION: Overview of the main APIs provided by Vite for plugin development, Hot Module Replacement, and general JavaScript integration. SOURCE: https://vite.dev/guide/api-environment LANGUAGE: APIDOC CODE: ``` Plugin API: Used for extending Vite's functionality through custom plugins. HMR API: Provides methods for managing Hot Module Replacement during development. JavaScript API: Offers programmatic access to Vite's features and configuration. ``` ---------------------------------------- TITLE: Vite build.cssTarget Configuration DESCRIPTION: Allows setting a specific browser target for CSS minification, separate from the JavaScript transpilation target. This is useful for non-mainstream browsers that might have different CSS feature support. For example, targeting `chrome61` can prevent transformation of `rgba()` to `#RGBA` hex notation. SOURCE: https://vite.dev/config/build-options LANGUAGE: APIDOC CODE: ``` build.cssTarget: Type: string | string[] Default: the same as [`build.target`](#build-target) Description: This option allows users to set a different browser target for CSS minification from the one used for JavaScript transpilation. It should only be used when targeting a non-mainstream browser. For example, Android WeChat WebView supports modern JS but not `#RGBA` hex colors in CSS, requiring `build.cssTarget` to be set to `chrome61` to prevent Vite from transforming `rgba()` colors. Example: // Target CSS for Chrome 61 compatibility // build: { // cssTarget: 'chrome61' // } ``` ---------------------------------------- TITLE: Vite HotUpdate Hook: Custom Event Example DESCRIPTION: Demonstrates using the `hotUpdate` hook to send a custom HMR event ('special-update') to the client for custom update logic, returning an empty array to prevent default handling. SOURCE: https://vite.dev/guide/api-environment-plugins LANGUAGE: js CODE: ``` hotUpdate() { if (this.environment.name !== 'client') return this.environment.hot.send({ type: 'custom', event: 'special-update', data: {} }) return [] } ``` ---------------------------------------- TITLE: Configure Vite Host for VS Code Devcontainers DESCRIPTION: Fixes issues with port forwarding in VS Code Dev Containers by setting the server host option. This is necessary because VS Code's port forwarding does not support IPv6. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: config CODE: ``` # vite.config.js or vite.config.ts import { defineConfig } from 'vite' export default defineConfig({ server: { host: '127.0.0.1' } }) ``` ---------------------------------------- TITLE: Resolve Static Asset URL DESCRIPTION: Demonstrates how to use `new URL` with `import.meta.url` to get the resolved URL of a static asset like an image. This pattern is natively supported by Vite for development and ensures correct asset paths after production bundling. SOURCE: https://vite.dev/guide/assets LANGUAGE: javascript CODE: ``` const imgUrl = new URL('./img.png', import.meta.url).href document.getElementById('hero-img').src = imgUrl ``` ---------------------------------------- TITLE: Deploy to Surge DESCRIPTION: Deploy your Vite static site using the Surge CLI. This involves building your project and then using the 'surge' command with the distribution directory. SOURCE: https://vite.dev/guide/static-deploy LANGUAGE: shell CODE: ``` npm run build surge dist ``` LANGUAGE: shell CODE: ``` surge dist yourdomain.com ``` ---------------------------------------- TITLE: Vite Build CLI Options DESCRIPTION: Configures the main Vite build process. These options control output directories, asset handling, source maps, minification, and watch modes. SOURCE: https://vite.dev/guide/cli LANGUAGE: APIDOC CODE: ``` Vite CLI Build Options: --target <target> Transpile target (default: "modules") (string) --outDir <dir> Output directory (default: dist) (string) --assetsDir <dir> Directory under outDir to place assets in (default: "assets") (string) --assetsInlineLimit <number> Static asset base64 inline threshold in bytes (default: 4096) (number) --ssr [entry] Build specified entry for server-side rendering (string) --sourcemap [output] Output source maps for build (default: false) (boolean | "inline" | "hidden") --minify [minifier] Enable/disable minification, or specify minifier to use (default: "esbuild") (boolean | "terser" | "esbuild") --manifest [name] Emit build manifest json (boolean | string) --ssrManifest [name] Emit ssr manifest json (boolean | string) --emptyOutDir Force empty outDir when it's outside of root (boolean) -w, --watch Rebuilds when modules have changed on disk (boolean) -c, --config <file> Use specified config file (string) --base <path> Public base path (default: "/") (string) -l, --logLevel <level> Info | warn | error | silent (string) --clearScreen Allow/disable clear screen when logging (boolean) --configLoader <loader> Use `bundle` to bundle the config with esbuild or `runner` (experimental) to process it on the fly (default: `bundle`) (string) --profile Start built-in Node.js inspector (check [Performance bottlenecks](/guide/troubleshooting#performance-bottlenecks)) -d, --debug [feat] Show debug logs (string | boolean) -f, --filter <filter> Filter debug logs (string) -m, --mode <mode> Set env mode (string) -h, --help Display available CLI options --app Build all environments, same as `builder: {}` (boolean, experimental) ``` ---------------------------------------- TITLE: Vite Preview Configuration Options DESCRIPTION: Comprehensive documentation for Vite's preview server configuration. This section details options for network binding, allowed hosts, port management, HTTPS, and automatic browser opening. SOURCE: https://vite.dev/config/preview-options LANGUAGE: APIDOC CODE: ``` Preview Options: Unless noted, the options in this section are only applied to preview. preview.host: - Type: string | boolean - Default: `server.host` - Description: Specify which IP addresses the server should listen on. Set this to `0.0.0.0` or `true` to listen on all addresses, including LAN and public addresses. This can be set via the CLI using `--host 0.0.0.0` or `--host`. - NOTE: There are cases when other servers might respond instead of Vite. See `server.host` for more details. preview.allowedHosts: - Type: string | true - Default: `server.allowedHosts` - Description: The hostnames that Vite is allowed to respond to. See `server.allowedHosts` for more details. preview.port: - Type: number - Default: 4173 - Description: Specify server port. Note if the port is already being used, Vite will automatically try the next available port so this may not be the actual port the server ends up listening on. - Example: export default defineConfig({ server: { port: 3030, }, preview: { port: 8080, }, }) preview.strictPort: - Type: boolean - Default: `server.strictPort` - Description: Set to `true` to exit if port is already in use, instead of automatically trying the next available port. preview.https: - Type: https.ServerOptions - Default: `server.https` - Description: Enable TLS + HTTP/2. See `server.https` for more details. preview.open: - Type: boolean | string - Default: `server.open` - Description: Automatically open the app in the browser on server start. When the value is a string, it will be used as the URL's pathname. If you want to open the server in a specific browser you like, you can set the env `process.env.BROWSER` (e.g. `firefox`). You can also set `process.env.BROWSER_ARGS` to pass additional arguments (e.g. `--incognito`). `BROWSER` and `BROWSER_ARGS` are also special environment variables you can set in the `.env` file to configure it. See [the `open` package](https://github.com/sindresorhus/open#app) for more details. ``` ---------------------------------------- TITLE: Deploy to Render DESCRIPTION: Deploy your Vite static site on Render. This involves creating a new Static Site, connecting a repository, and specifying the build command and publish directory. SOURCE: https://vite.dev/guide/static-deploy LANGUAGE: shell CODE: ``` # Build Command: npm install && npm run build # Publish Directory: dist ``` ---------------------------------------- TITLE: Update package.json dev script (Diff) DESCRIPTION: This diff shows how to modify the `dev` script in `package.json`. Instead of running Vite directly, it now executes the custom `server.js` script. This ensures that the Node.js server, configured with Vite in middleware mode, is started when you run `npm run dev`. SOURCE: https://vite.dev/guide/ssr LANGUAGE: diff CODE: ``` "scripts": { - "dev": "vite" + "dev": "node server" } ``` ---------------------------------------- TITLE: Deploy to Kinsta DESCRIPTION: Deploy your static site using Kinsta Static Site Hosting by following their provided instructions for React and Vite applications. SOURCE: https://vite.dev/guide/static-deploy LANGUAGE: shell CODE: ``` # Follow Kinsta's guide for Vite quickstart. ``` ---------------------------------------- TITLE: Configure Vite Server Proxy Rules DESCRIPTION: Defines custom proxy rules for the Vite development server. Supports string shorthand, options objects, and RegExp for flexible request routing. Any requests starting with a configured key will be proxied to the specified target. Extends http-proxy options. SOURCE: https://vite.dev/config/server-options LANGUAGE: javascript CODE: ``` export default defineConfig({ server: { proxy: { // string shorthand: // http://localhost:5173/foo // -> http://localhost:4567/foo '/foo': 'http://localhost:4567', // with options: // http://localhost:5173/api/bar // -> http://jsonplaceholder.typicode.com/bar '/api': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ''), }, // with RegExp: // http://localhost:5173/fallback/ // -> http://jsonplaceholder.typicode.com/ '^/fallback/.*': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, rewrite: (path) => path.replace(/^\/fallback/, ''), }, // Using the proxy instance '/api': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, configure: (proxy, options) => { // proxy will be an instance of 'http-proxy' }, }, // Proxying websockets or socket.io: // ws://localhost:5173/socket.io // -> ws://localhost:5174/socket.io // Exercise caution using `rewriteWsOrigin` as it can leave the // proxying open to CSRF attacks. '/socket.io': { target: 'ws://localhost:5174', ws: true, rewriteWsOrigin: true, }, }, }, }) ``` ---------------------------------------- TITLE: Spin up a Vite-powered app DESCRIPTION: Command to quickly create a new Vite project. Requires Node.js version 12 or higher. SOURCE: https://vite.dev/blog/announcing-vite2 LANGUAGE: bash CODE: ``` npm init @vitejs/app ``` ---------------------------------------- TITLE: Vite Build and Preview Scripts DESCRIPTION: Defines npm scripts for building a Vite application (`vite build`) and previewing the production build locally (`vite preview`). These are essential for managing the build and deployment process. SOURCE: https://vite.dev/guide/static-deploy LANGUAGE: json CODE: ``` { "scripts": { "build": "vite build", "preview": "vite preview" } } ``` ---------------------------------------- TITLE: Patching Dependencies for Strict Mode Issues DESCRIPTION: When encountering errors related to strict mode in dependencies (e.g., `with` statements), you can use patching tools like `patch-package`, `yarn patch`, or `pnpm patch` to modify the dependency code. This acts as an escape hatch for incompatible code. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: bash CODE: ``` npm install patch-package postinstall-postinstall ``` LANGUAGE: bash CODE: ``` npx patch-package <package-name> ``` LANGUAGE: bash CODE: ``` yarn patch <package-name> ``` LANGUAGE: bash CODE: ``` pnpm patch <package-name> ``` ---------------------------------------- TITLE: Vite build.lib Configuration DESCRIPTION: Configures Vite to build the project as a library. It allows specifying entry points, library name, output formats, and file names for JavaScript and CSS. SOURCE: https://vite.dev/config/build-options LANGUAGE: APIDOC CODE: ``` build.lib: Type: { entry: string | string[] | { [entryAlias: string]: string }, name?: string, formats?: ('es' | 'cjs' | 'umd' | 'iife')[], fileName?: string | ((format: ModuleFormat, entryName: string) => string), cssFileName?: string } Related: [Library Mode](/guide/build#library-mode) Description: Build as a library. `entry` is required since the library cannot use HTML as entry. `name` is the exposed global variable and is required when `formats` includes 'umd' or 'iife'. Default `formats` are ['es', 'umd'], or ['es', 'cjs'], if multiple entries are used. `fileName` is the name of the package file output, which defaults to the "name" in `package.json`. It can also be defined as a function taking the `format` and `entryName` as arguments, and returning the file name. If your package imports CSS, `cssFileName` can be used to specify the name of the CSS file output. It defaults to the same value as `fileName` if it's set a string, otherwise it also falls back to the "name" in `package.json`. ``` LANGUAGE: js CODE: ``` import { defineConfig } from 'vite' export default defineConfig ({ build: { lib: { entry: ['src/main.js'], fileName: ( format, entryName ) => `my-lib-${ entryName }.${ format }.js`, cssFileName: 'my-lib-style' } } }) ``` ---------------------------------------- TITLE: Node.js Conditional Exports Example DESCRIPTION: Illustrates the `exports` field in `package.json` and how Vite's `resolve.conditions` option interacts with it. Conditional exports allow packages to specify different entry points based on environment or module type (e.g., 'import', 'require'). SOURCE: https://vite.dev/config/shared-options LANGUAGE: json CODE: ``` { "exports": { ".": { "import": "./index.mjs", "require": "./index.js" } } } ``` LANGUAGE: APIDOC CODE: ``` resolve.conditions: Type: string[] Default: ['module', 'browser', 'development|production'] Description: Additional conditions for resolving Conditional Exports from packages. The `development|production` value is dynamically replaced based on `process.env.NODE_ENV`. 'import', 'require', and 'default' conditions are always applied if met. ``` ---------------------------------------- TITLE: Vite: Create and Use FetchableDevEnvironment DESCRIPTION: Demonstrates creating a Vite server with a custom `FetchableDevEnvironment` that handles requests via the Fetch API. It shows importing necessary functions, configuring the environment, and dispatching a fetch request. The environment requires `Request` and `Response` instances for `dispatchFetch`, and Vite will validate these types. SOURCE: https://vite.dev/guide/api-environment-frameworks LANGUAGE: typescript CODE: ``` import { createServer, createFetchableDevEnvironment, isFetchableDevEnvironment, } from 'vite' const server = await createServer({ server: { middlewareMode: true }, appType: 'custom', environments: { custom: { dev: { createEnvironment(name, config) { return createFetchableDevEnvironment(name, config, { handleRequest(request: Request): Promise<Response> | Response { // handle Request and return a Response }, }) }, }, }, }, }) // Any consumer of the environment API can now call `dispatchFetch` if (isFetchableDevEnvironment(server.environments.custom)) { const response: Response = await server.environments.custom.dispatchFetch( new Request('/request-to-handle'), ) } ``` ---------------------------------------- TITLE: Build Vite Application DESCRIPTION: Executes the Vite build command to generate production-ready static assets. The output is typically placed in the 'dist' directory, ready for deployment. SOURCE: https://vite.dev/guide/static-deploy LANGUAGE: bash CODE: ``` $ npm run build ``` ---------------------------------------- TITLE: Vite SSR: Run Entrypoint in Custom Dev Environment DESCRIPTION: Demonstrates setting up a Vite development server with a plugin to handle virtual modules. It shows how to interact with a custom SSR environment, specifically checking for `CustomDevEnvironment` and running an entrypoint module. SOURCE: https://vite.dev/guide/api-environment-frameworks LANGUAGE: ts CODE: ``` import { createServer } from 'vite' const server = createServer({ plugins: [ // a plugin that handles `virtual:entrypoint` { name: 'virtual-module', /* plugin implementation */ }, ], }) const ssrEnvironment = server.environment.ssr const input = {} // use exposed functions by each environment factories that runs the code // check for each environment factories what they provide if (ssrEnvironment instanceof CustomDevEnvironment) { ssrEnvironment.runEntrypoint('virtual:entrypoint') } else { throw new Error(`Unsupported runtime for ${ssrEnvironment.name}`) } // ------------------------------------- // virtual:entrypoint const { createHandler } = await import('./entrypoint.js') const handler = createHandler(input) const response = handler(new Request('/')) // ------------------------------------- // ./entrypoint.js export function createHandler(input) { return function handler(req) { return new Response('hello') } } ``` ---------------------------------------- TITLE: Vite `importedChunks` Pseudo Implementation (TypeScript) DESCRIPTION: A pseudo-implementation in TypeScript for a function that resolves all imported chunks recursively starting from a given entry point name. This function helps in identifying all CSS and JavaScript files needed for a specific entry point, which is crucial for generating the correct HTML tags. SOURCE: https://vite.dev/guide/backend-integration LANGUAGE: typescript CODE: ``` import type { Manifest, ManifestChunk } from 'vite' export default function importedChunks( manifest: Manifest, name: string, ): ManifestChunk[] { const seen = new Set<string>() function getImportedChunks(chunk: ManifestChunk): ManifestChunk[] { const chunks: ManifestChunk[] = [] for (const file of chunk.imports ?? []) { const importee = manifest[file] if (seen.has(file)) { continue } seen.add(file) chunks.push(...getImportedChunks(importee)) chunks.push(importee) } return chunks } return getImportedChunks(manifest[name]) } ``` ---------------------------------------- TITLE: HMR Case Sensitivity Issue DESCRIPTION: Addresses Hot Module Replacement (HMR) failures when importing files with incorrect casing. Vite's HMR might not update if the imported file name casing differs from the actual file name. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: js CODE: ``` // Incorrect import (e.g., src/foo.js exists, but imported as Foo.js) import './Foo.js' // Correct import // import './foo.js' ``` ---------------------------------------- TITLE: Vite build.ssr Option DESCRIPTION: Configures Vite to produce an SSR-oriented build. The entry point for SSR can be specified directly or via rollupOptions.input. SOURCE: https://vite.dev/config/build-options LANGUAGE: APIDOC CODE: ``` build.ssr: Type: boolean | string Default: false Related: [Server-Side Rendering](/guide/ssr) Description: Produce SSR-oriented build. The value can be a string to directly specify the SSR entry, or `true`, which requires specifying the SSR entry via `rollupOptions.input`. ``` ---------------------------------------- TITLE: Vite optimizeDeps.holdUntilCrawlEnd Configuration DESCRIPTION: An experimental option that, when enabled (defaulting to true), delays the release of the first optimized dependency results until all static imports have been crawled on a cold start. This prevents full-page reloads caused by newly discovered dependencies generating new common chunks. Disabling this can allow the browser to process more requests in parallel if all dependencies are found early. SOURCE: https://vite.dev/config/dep-optimization-options LANGUAGE: APIDOC CODE: ``` optimizeDeps.holdUntilCrawlEnd Type: boolean Default: true Experimental: Yes Description: When enabled, it will hold the first optimized deps results until all static imports are crawled on cold start. This avoids the need for full-page reloads when new dependencies are discovered and they trigger the generation of new common chunks. If all dependencies are found by the scanner plus the explicitly defined ones in `include`, it is better to disable this option to let the browser process more requests in parallel. ``` ---------------------------------------- TITLE: Vite optimizeDeps.needsInterop Configuration DESCRIPTION: An experimental option to force ESM interop for specific dependencies. Vite typically detects the need for interop automatically, but this array can be used to manually specify packages that require it, potentially speeding up cold starts by avoiding full-page reloads. A warning will be issued if Vite detects a dependency might benefit from being added to this list. SOURCE: https://vite.dev/config/dep-optimization-options LANGUAGE: APIDOC CODE: ``` optimizeDeps.needsInterop Type: string[] Experimental: Yes Description: Forces ESM interop when importing these dependencies. Vite is able to properly detect when a dependency needs interop, so this option isn't generally needed. However, different combinations of dependencies could cause some of them to be prebundled differently. Adding these packages to `needsInterop` can speed up cold start by avoiding full-page reloads. You'll receive a warning if this is the case for one of your dependencies, suggesting to add the package name to this array in your config. ``` ---------------------------------------- TITLE: Adjust Max HTTP Header Size DESCRIPTION: Mitigates '431 Request Header Fields Too Large' errors in Node.js by allowing adjustment of the maximum HTTP header size. This can be done via a CLI flag or by reducing header content like cookies. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: shell CODE: ``` # Example of changing max header size via CLI flag: # vite --max-http-header-size=8000 # Alternatively, reduce header size by removing large cookies or other data. ``` ---------------------------------------- TITLE: Force Re-optimization of Dependencies DESCRIPTION: When linking local packages or making changes that Vite's dependency optimization might miss, you can force Vite to re-optimize dependencies. This is often necessary after using `npm link` or similar tools. Using `vite --force` triggers a full re-optimization. SOURCE: https://vite.dev/guide/troubleshooting LANGUAGE: bash CODE: ``` vite --force ``` ---------------------------------------- TITLE: ViteDevServer Interface DESCRIPTION: The ViteDevServer interface defines the core object for the Vite development server. It exposes properties for accessing the Vite configuration, Connect middleware, Node.js http server, file watcher, WebSocket server, plugin container, module graph, and resolved URLs. It also includes methods for programmatically transforming requests, transforming HTML, loading modules for SSR, fixing stack traces, reloading modules, starting, restarting, and closing the server, and binding CLI shortcuts. The `waitForRequestsIdle` method is an experimental feature to wait for static imports to be processed. SOURCE: https://vite.dev/guide/api-javascript LANGUAGE: APIDOC CODE: ``` ViteDevServer: config: ResolvedConfig - The resolved Vite config object. middlewares: Connect.Server - A connect app instance. - Can be used to attach custom middlewares to the dev server. - Can also be used as the handler function of a custom http server or as a middleware in any connect-style Node.js frameworks. - https://github.com/senchalabs/connect#use-middleware httpServer: http.Server | null - Native Node http server instance. - Will be null in middleware mode. watcher: FSWatcher - Chokidar watcher instance. If `config.server.watch` is set to `null`, it will not watch any files and calling `add` or `unwatch` will have no effect. - https://github.com/paulmillr/chokidar/tree/3.6.0#api ws: WebSocketServer - Web socket server with `send(payload)` method. pluginContainer: PluginContainer - Rollup plugin container that can run plugin hooks on a given file. moduleGraph: ModuleGraph - Module graph that tracks the import relationships, url to file mapping and hmr state. resolvedUrls: ResolvedServerUrls | null - The resolved urls Vite prints on the CLI (URL-encoded). Returns `null` in middleware mode or if the server is not listening on any port. transformRequest(url: string, options?: TransformOptions): Promise<TransformResult | null> - Programmatically resolve, load and transform a URL and get the result without going through the http request pipeline. transformIndexHtml(url: string, html: string, originalUrl?: string): Promise<string> - Apply Vite built-in HTML transforms and any plugin HTML transforms. ssrLoadModule(url: string, options?: { fixStacktrace?: boolean }): Promise<Record<string, any>> - Load a given URL as an instantiated module for SSR. ssrFixStacktrace(e: Error): void - Fix ssr error stacktrace. reloadModule(module: ModuleNode): Promise<void> - Triggers HMR for a module in the module graph. You can use the `server.moduleGraph` API to retrieve the module to be reloaded. If `hmr` is false, this is a no-op. listen(port?: number, isRestart?: boolean): Promise<ViteDevServer> - Start the server. restart(forceOptimize?: boolean): Promise<void> - Restart the server. - @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag close(): Promise<void> - Stop the server. bindCLIShortcuts(options?: BindCLIShortcutsOptions<ViteDevServer>): void - Bind CLI shortcuts waitForRequestsIdle: (ignoredId?: string) => Promise<void> - Calling `await server.waitForRequestsIdle(id)` will wait until all static imports are processed. If called from a load or transform plugin hook, the id needs to be passed as a parameter to avoid deadlocks. Calling this function after the first static imports section of the module graph has been processed will resolve immediately. - @experimental - INFO: `waitForRequestsIdle` is meant to be used as a escape hatch to improve DX for features that can't be implemented following the on-demand nature of the Vite dev server. It can be used during startup by tools like Tailwind to delay generating the app CSS classes until the app code has been seen, avoiding flashes of style changes. When this function is used in a load or transform hook, and the default HTTP1 server is used, one of the six http channels will be blocked until the server processes all static imports. Vite's dependency optimizer currently uses this function to avoid full-page reloads on missing dependencies by delaying loading of pre-bundled dependencies until all imported dependencies have been collected from static imported sources. Vite may switch to a different strategy in a future major release, setting `optimizeDeps.crawlUntilStaticImports: false` by default to avoid the performance hit in large applications during cold start. ``` |