### Start Pareto.js Production Server Source: https://paretojs.tech/guide/start/quick-start Starts the production server using the already built production bundle of a Pareto.js project. This command is typically used after running the 'npm run build' command. ```bash npm run start ``` -------------------------------- ### Report Data and Use FirstScreen Component (TypeScript) Source: https://paretojs.tech/guide/builtIn/monitor This example illustrates how to report data using the `report` function and render the `FirstScreen` component within a Pareto page component. It includes a `useEffect` hook to report data on component mount. ```typescript import { report, FirstScreen } from '@paretojs/monitor' const Home: ParetoPage = props => { const { repositories } = props.initialData useEffect(() => { report().then(console.log) }, []) return ( <>
...
) } ``` -------------------------------- ### Start Pareto.js Development Server Source: https://paretojs.tech/guide/start/quick-start Starts the local development server for a Pareto.js project. This command allows for hot-reloading and other development-specific features. The port and host can be customized using the --port and --host flags. ```bash npm run dev # Example with custom port and host: pareto dev --port 8080 --host 0.0.0.0 ``` -------------------------------- ### Build Pareto.js Project for Production Source: https://paretojs.tech/guide/start/quick-start Builds the production-ready bundle for a Pareto.js project. This command optimizes the code for deployment. By default, the output is placed in the .pareto directory. ```bash npm run build ``` -------------------------------- ### Install Lingui and related packages for i18n Source: https://paretojs.tech/guide/features/i18n Installs the necessary Lingui packages and development dependencies for internationalization using pnpm. ```bash pnpm i @lingui/cli @lingui/macro @types/accepts -D pnpm i babel-plugin-macros @lingui/core @lingui/react accepts ``` -------------------------------- ### Install Tailwind CSS with npm Source: https://paretojs.tech/guide/builtIn/css Installs the Tailwind CSS development dependency and runs the initialization command to create configuration files. ```bash npm install -D tailwindcss npx tailwindcss init -p ``` -------------------------------- ### Initialize a Pareto.js Project with npm Source: https://paretojs.tech/guide/start/quick-start Initializes a new Pareto.js project using the create-pareto CLI via npm. This command prompts the user for a project directory name and sets up the project structure. ```bash npm create pareto@latest ``` -------------------------------- ### Setup Client-Side Promise Mocking (JavaScript) Source: https://paretojs.tech/guide/features/stream Sets up a mock client-side promise that synchronizes with the server's stream data. This ensures that the client can correctly handle and display data as it arrives. ```javascript Home.setUpClient = async () => { // mock client promise, it only will be resolved when server stream data is ready mockClientPromise(getRecommendsKey) } ``` -------------------------------- ### Configure client entry for Lingui initialization Source: https://paretojs.tech/guide/features/i18n Modifies the `client-entry.tsx` to call `initLinguiClient()` after the application starts, ensuring that Lingui is initialized with the locale and messages passed from the server. ```typescript import { I18nProvider } from '@lingui/react' import { i18n } from '@lingui/core' import { initLinguiClient } from './i18n' const startApp = async (Page: ParetoPage) => { const root = document.getElementById('main') as HTMLElement const __INITIAL_DATA__ = window.__INITIAL_DATA__ as Record initLinguiClient() await Page.setUpClient?.() hydrateRoot( root, , ) } ``` -------------------------------- ### Enable Monitor in Pareto Configuration (TypeScript) Source: https://paretojs.tech/guide/builtIn/monitor This code snippet shows how to enable the monitoring feature by setting `enableMonitor` to `true` in the `pareto.config.ts` file. This is a configuration step for the Pareto project. ```typescript import { ParetoConfig } from '@paretojs/core/config' const config: ParetoConfig = { enableMonitor: true, } export default config ``` -------------------------------- ### Integrate Monitor Middleware in Server Entry (TypeScript) Source: https://paretojs.tech/guide/builtIn/monitor This snippet demonstrates how to integrate the monitor middleware into the Express server using `createMonitorMiddleware`. It shows how to control the visibility of the monitor UI via the `showMonitor` option. ```typescript import { createMonitorMiddleware } from '@paretojs/core/node' import express from 'express' const app = express() app.use( createMonitorMiddleware({ // control whether to display the UI in the front end showMonitor: true, }), ) ``` -------------------------------- ### Basic React Component with SCSS Source: https://paretojs.tech/guide/features/critical-css Demonstrates a standard React component utilizing SCSS modules for styling. This example shows how CSS is typically imported and applied using a module system. ```jsx import styles from './style.module.scss' const Component = () => { return (

Hello World

) } ``` ```css .container { background-color: #f0f0f0; } .title { color: #333; } ``` -------------------------------- ### Setup Server-Side Promise Map (TypeScript) Source: https://paretojs.tech/guide/features/stream Configures the server-side promise map to manage the status of stream requests. It allows asynchronous operations to be initiated without blocking the initial server render. ```typescript Home.getServerSideProps = async () => { // we don't need wait for stream request promiseMap.set(getRecommendsKey, getRecommends()) // request that need wait const repositories = await fetch('/api/repositories') return repositories } ``` -------------------------------- ### Enable Streaming Rendering in React 17 & 16.8 with ParetoJS (Example) Source: https://paretojs.tech/guide/start/introduction ParetoJS does not directly support React 17, but streaming rendering can be enabled in versions after React 16.8. This example provides a rough integration for older React versions. ```javascript # This section provides a conceptual example and does not contain direct runnable code. # Refer to the project documentation for a complete implementation. # Example structure: # import React from 'react'; # import { renderToPipeableStream } from 'react-dom/server'; # # const App = () => ( #
#

Hello from ParetoJS

#
# ); # # renderToPipeableStream(, { # onComplete: () => { # // Handle completion # }, # onError: (error) => { # // Handle error # } # }); ``` -------------------------------- ### Set Page Title using React Helmet Async Source: https://paretojs.tech/guide/features/meta This example demonstrates how to set the page title for a React component using the Helmet provider from react-helmet-async. Ensure react-helmet-async is installed as a dependency. This component will automatically update the document's title during server-side rendering. ```jsx import { Helmet } from 'react-helmet-async' const App = () => { return ( <> Home
hello world
) } ``` -------------------------------- ### Define Stream Request and Key (TypeScript) Source: https://paretojs.tech/guide/features/stream Defines a key and an asynchronous function to fetch recommendations. This is the first step in setting up stream rendering, identifying which requests are candidates for streaming. ```typescript // data.ts export const getRecommendsKey = 'getRecommends' export const getRecommends = () => fetch('/api/recommends') ``` -------------------------------- ### Consume Promises with Suspense (React) Source: https://paretojs.tech/guide/features/stream Demonstrates how to consume promises using React's Suspense and the `use` hook for stream rendering. It shows how to handle loading states with a fallback component. ```javascript // React19 import { use } from 'react' // React18 import { use } from '@paretojs/core' const Home = () => { return (
hello world
}>
) } const Recommends = () => { const { feeds } = use(promiseMap.get(getRecommendsKey)!) return (
Recommends
{feeds.map((item, index) => (
...
))}
) } ``` -------------------------------- ### Adding Static Assets with getAsset in React (JavaScript) Source: https://paretojs.tech/guide/features/static-asset This example demonstrates how to use the `getAsset` method within a React component to define static resources for a page. The `getAsset` function returns an array of asset objects, each specifying a type and URL. ParetoJS will convert these into link tags for early browser loading. ```javascript const Home: ParetoPage = () => { return (

Home

) } Home.getAssets = () => { return [ { type: 'image', url: 'https://example.com/image.jpg', }, ] } ``` -------------------------------- ### Share Common Meta Tags Across Routes with React Helmet Async Source: https://paretojs.tech/guide/features/meta This example shows how to define and share common meta tags, such as titles, canonical links, and Open Graph tags, across multiple routes. A `shared-meta.tsx` file is created and then imported into both `client-entry.tsx` and `server-entry.tsx` to ensure consistent metadata application. ```tsx // shared-meta.tsx import { Helmet } from 'react-helmet-async' const Meta = () => { return ( A fancy webpage ) } export default Meta ``` ```tsx // client-entry.tsx hyhydrateRoot( root, , ) ``` ```javascript // server-entry.tsx app.get( '*', paretoRequestHandler({ delay: ABORT_DELAY, pageWrapper: Page => { return props => ( <> ) }, }), ) ``` -------------------------------- ### Lingui i18n utility functions Source: https://paretojs.tech/guide/features/i18n Provides utility functions for loading message catalogs, initializing Lingui on the server, and initializing Lingui on the client by accessing global window variables. ```typescript import { i18n, Messages } from '@lingui/core' export function loadCatalog(page: string, locale: string) { /* when you need to load messages in production, ** You can use a script after pnpm build to move the contents of the locales folder ** into the .pareto folder and modify the import paths here. */ const data = require(`./app/${page}/locales/${locale}/messages`) return data.messages } export function initLinguiServer(messages: Messages, locale: string) { if (locale !== i18n.locale) { i18n.loadAndActivate({ locale, messages }) } } export function initLinguiClient() { const locale = window.__LOCALE__ const messages = window.__LOCALE_MESSAGE__ i18n.load(locale, messages) i18n.activate(locale) } ``` -------------------------------- ### Conditional Rendering with Different Components Source: https://paretojs.tech/guide/features/critical-css Illustrates a simple A/B testing scenario where different React components are rendered based on a condition. This highlights a situation where unnecessary CSS might be loaded. ```jsx const ABTestComponent = () => { return ab ? : } ``` -------------------------------- ### Define scripts for Lingui message extraction and compilation Source: https://paretojs.tech/guide/features/i18n Adds scripts to `package.json` for running Lingui's `extract` and `compile` commands to manage translation messages. ```json { "scripts": { "extract": "lingui extract", "compile": "lingui compile" } } ``` -------------------------------- ### Configure Lingui for message extraction Source: https://paretojs.tech/guide/features/i18n Sets up the Lingui configuration file (`lingui.config.js`) to define supported locales, source locale, catalog paths, and message format. ```javascript /** @type {import('@lingui/conf').LinguiConfig} */ module.exports = { locales: ['en', 'zh'], sourceLocale: 'en', catalogs: [ { path: '/app/{name}/locales/{locale}/messages', include: ['/app/{name}/'], }, ], format: 'po', } ``` -------------------------------- ### Define Styles for Custom 404 Page (SCSS) Source: https://paretojs.tech/guide/features/custom This SCSS file provides styling for the custom 404 page. It defines flexbox layout for centering content, font styles, and hover effects for the back-to-home link. ```scss .not-found-container { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; text-align: center; font-family: Arial, sans-serif; } .error-code { font-size: 8rem; font-weight: bold; color: #333; } .error-message { margin-top: 20px; font-size: 1.5rem; color: #666; } .back-link { margin-top: 30px; } .back-link a { text-decoration: none; color: #007bff; font-weight: bold; transition: color 0.3s ease; } .back-link a:hover { color: #0056b3; } ``` -------------------------------- ### TypeScript definitions for Lingui integration Source: https://paretojs.tech/guide/features/i18n Defines global types for window objects (`__INITIAL_DATA__`, `__LOCALE__`, `__LOCALE_MESSAGE__`) used for internationalization data passing between server and client. ```typescript /// /// declare global { interface Window { __INITIAL_DATA__: any __LOCALE__: string __LOCALE_MESSAGE__: any } } export {} ``` -------------------------------- ### Import Tailwind CSS Global Styles Source: https://paretojs.tech/guide/builtIn/css Imports Tailwind's base, components, and utilities directives into a global CSS file (`index.css`) and then imports this file into the client entry point (`client-entry.tsx`) to apply styles application-wide. ```css // index.css @tailwind base; @tailwind components; @tailwind utilities; ``` ```javascript // client-entry.tsx import "./index.css"; const startApp = async (Page: ParetoPage) => { ... }; export { startApp }; ``` -------------------------------- ### Use Tailwind CSS Utility Classes in a React Component Source: https://paretojs.tech/guide/builtIn/css Demonstrates applying Tailwind CSS utility classes directly within a JSX element in a React component (`app/home/index.tsx`) after setup is complete. ```javascript // app/home/index.tsx export default function Page() { return

Hello, Pareto!

} ``` -------------------------------- ### Import Tailwind CSS Directives Source: https://paretojs.tech/guide/builtin/css Includes the necessary Tailwind CSS directives (@tailwind base, @tailwind components, @tailwind utilities) in a global stylesheet (e.g., index.css). These directives are used to inject Tailwind's generated styles into the application. ```css // index.css @tailwind base; @tailwind components; @tailwind utilities; ``` -------------------------------- ### Enable Critical CSS with useStyles Hook Source: https://paretojs.tech/guide/features/critical-css Shows how to enable critical CSS collection using the `useStyles` hook from `@pareto/core` with SCSS files ending in `.iso.scss`. This approach selectively collects necessary styles during rendering. ```jsx import styles from './style.iso.scss' import { useStyles } from '@pareto/core' const Component = () => { useStyles(styles) return (

Hello World

) } ``` -------------------------------- ### Enable Streaming Rendering in React 18 with ParetoJS Source: https://paretojs.tech/guide/start/introduction When using React 18 with ParetoJS, you need to use the `use` function exported from `@paretojs/core` to enable streaming rendering, as the `use` hook is not exposed in React 18. ```javascript import { use } from '@paretojs/core' ``` -------------------------------- ### Create Custom 404 Page Component (React/TSX) Source: https://paretojs.tech/guide/features/custom This React component defines the structure and content for the custom 404 page. It includes a title, an error message, and a link back to the home page. It also imports a SCSS file for styling. ```tsx import './style.scss' const NotFound: React.FC = () => { return (
404
Oops! Page not found.
); }; export default NotFound; ``` -------------------------------- ### Configure Server Entry for 404 Redirection (Node.js/TS) Source: https://paretojs.tech/guide/features/custom This Node.js code snippet modifies the server entry point (`server-entry.tsx`) to handle requests for undefined routes. If a requested path is not found in `pageRoutes`, it redirects the user to the '/notFound' route. Otherwise, it proceeds with the standard ParetoJS request handling. ```typescript import { pageRoutes, paretoRequestHandler } from '@paretojs/core/node' app.get('*', async (req, res) => { const route = req.path.slice(1) if(!pageRoutes.includes(route)) { res.redirect('/notFound'); return } const handler = paretoRequestHandler({ delay: ABORT_DELAY, }) await handler(req, res) }) ``` -------------------------------- ### Critical CSS Pitfall: useStyles Order Source: https://paretojs.tech/guide/features/critical-css Demonstrates a potential pitfall when using critical CSS with stream rendering. It emphasizes the importance of placing `useStyles` calls before the `use` function to ensure server-side style collection. ```jsx export function Recommends() { useStyles(styles) // Recommend: always place useStyles in top; const { feeds } = use(promiseMap.get(getRecommendsKey)!) return
...
} ``` -------------------------------- ### Import Global Stylesheet in Client Entry Source: https://paretojs.tech/guide/builtin/css Imports the global stylesheet (containing Tailwind CSS directives) into the client entry file (e.g., client-entry.tsx). This ensures that the Tailwind styles are applied to all routes in the application. ```typescript // client-entry.tsx import "./index.css"; const startApp = async (Page: ParetoPage) => { ... }; export { startApp }; ``` -------------------------------- ### Configure server entry for dynamic i18n message loading Source: https://paretojs.tech/guide/features/i18n Modifies the `server-entry.tsx` to determine the user's locale, load corresponding messages using `loadCatalog`, initialize Lingui on the server with `initLinguiServer`, and pass locale data to the client via a script tag. ```typescript import accepts from 'accepts' import { initLinguiServer, loadCatalog } from './i18n' import { I18nProvider } from '@lingui/react' import { i18n } from '@lingui/core' const app = express() const ABORT_DELAY = 5_000 app.get('*', async (req, res, next) => { const path = req.path.slice(1) const accept = accepts(req) const locale = accept.language(['en', 'zh']) || 'en' const messages = loadCatalog(path, locale) initLinguiServer(messages, locale) const handler = paretoRequestHandler({ delay: ABORT_DELAY, pageWrapper: Page => { return props => (