### Manual Project Setup: Start Application with Node.js Source: https://markojs.com/docs/introduction/installation Starts the application by running the Express server script using Node.js. This command assumes the server logic is saved in 'index.js'. ```bash node index.js ``` -------------------------------- ### Manual Project Setup: Install Express Server Dependency Source: https://markojs.com/docs/introduction/installation Installs the Express.js framework, which will be used to create a basic server for handling requests and rendering Marko pages. ```bash npm install express ``` -------------------------------- ### Manual Project Setup: Create Directory and Initialize Package Source: https://markojs.com/docs/introduction/installation Creates a new project directory and initializes a package.json file using npm. This is the first step in a manual Marko project setup. ```bash mkdir my-marko-application cd my-marko-application npm init --yes ``` -------------------------------- ### Install Marko Run Package (npm) Source: https://markojs.com/docs/marko-run/getting-started Installs the Marko Run package using npm. This is required for both new projects starting from zero and for adding Marko Run to existing Marko projects. ```sh npm install @marko/run ``` -------------------------------- ### Manual Project Setup: Install Marko and Vite Dependencies Source: https://markojs.com/docs/introduction/installation Installs Marko as a project dependency and Vite with its Marko plugin as development dependencies. Requires Node.js and npm. ```bash npm install marko@next npm install -D vite @marko/vite ``` -------------------------------- ### Preview Production Build with Marko Run (npm exec) Source: https://markojs.com/docs/marko-run/getting-started Builds the application for production and starts a local preview server. This is useful for testing the production build before deploying. ```sh npm exec marko-run preview ``` -------------------------------- ### Initialize New Marko Project with Marko Run Source: https://markojs.com/docs/introduction/installation Uses npm to initialize a new Marko project with the 'basic' template and starts the development server. Requires Node.js and npm. ```bash npm init marko -- -t basic cd ./my-marko-application npm run dev ``` -------------------------------- ### Start Marko Run Development Server (npm exec) Source: https://markojs.com/docs/marko-run/getting-started Starts the Marko Run development server using npm exec. This command enables watch mode for rapid development and hot module replacement. ```sh npm exec marko-run ``` ```sh npm exec marko-run dev ``` -------------------------------- ### Manual Project Setup: First Marko Page Content Source: https://markojs.com/docs/introduction/installation Defines the basic HTML structure for the root Marko page ('src/routes/index.marko'). This file serves as the entry point for the web application's UI. ```marko

Hello Marko!

``` -------------------------------- ### Initialize Marko Project with Template (npm) Source: https://markojs.com/docs/marko-run/getting-started Initializes a new Marko project using a specified template via npm. This is a common starting point for new Marko applications, often including Marko Run by default. ```sh npm init marko -- -t basic ``` -------------------------------- ### Build Production Artifacts with Marko Run (npm exec) Source: https://markojs.com/docs/marko-run/getting-started Creates a production-ready build of the Marko Run application. This command optimizes assets and prepares the application for deployment. ```sh npm exec marko-run build ``` -------------------------------- ### Manual Project Setup: Express Server with Vite SSR Source: https://markojs.com/docs/introduction/installation Sets up an Express server that integrates with Vite's Server-Side Rendering (SSR) capabilities to render Marko components. This code is intended for development environments. ```javascript import express from "express"; import { createServer } from "vite"; const app = express(); const vite = await createServer({ server: { middlewareMode: true, }, appType: "custom", }); app.use(vite.middlewares); app.get("/", async (req, res) => { const template = ( await vite.ssrLoadModule("./src/routes/index.marko?marko-server-entry") ).default; const result = template.render(); res.header("Content-Type", "text/html"); result.pipe(res); }); app.listen(3000); ``` -------------------------------- ### Inline SCSS and LESS Styles in Marko Source: https://markojs.com/docs/guide/styling Shows how to use SCSS and LESS preprocessors with the `
Hello!
@primary-color: blue; .fancy-less { color: @primary-color; }
Hello!
``` -------------------------------- ### Manual Project Setup: Vite Configuration with Marko Plugin Source: https://markojs.com/docs/introduction/installation Configures Vite to use the Marko plugin by creating a vite.config.ts file. This enables Marko rendering within the Vite build process. ```typescript import { defineConfig } from "vite"; import marko from "@marko/vite"; export default defineConfig({ plugins: [marko()], }); ``` -------------------------------- ### Marko.js Middleware Function Example Source: https://markojs.com/docs/marko-run/file-based-routing Provides an example of a '+middleware.ts' file, demonstrating how to implement middleware for request handling. This example logs request start and completion, and includes error handling using a try-catch-finally block. ```typescript /* +middleware.ts */ export default async function (context, next) { const requestName = `${context.request.method} ${context.url.href}`; let success = true; console.log(`${requestName} request started`); try { return await next(); // Wait for subsequent middleware, handler, and page } catch (err) { success = false; throw err; } finally { console.log( `${requestName} completed ${success ? "successfully" : "with errors"}`, ); } } ``` -------------------------------- ### Basic Inline Styles in Marko Source: https://markojs.com/docs/guide/styling Demonstrates using the `
Hello!
``` -------------------------------- ### Marko: Styling with CSS and Dynamic Styles Source: https://markojs.com/docs/tutorial/components-and-reactivity Shows how to add styles directly within a Marko template using the ` ``` -------------------------------- ### Basic HTML Template in Marko Source: https://markojs.com/docs/tutorial/fundamentals Marko templates are largely compatible with standard HTML. This example shows a simple HTML structure for a blog header and navigation within a Marko file. ```marko

My Blog

``` -------------------------------- ### Marko Installed Tag Configuration (marko.json) Source: https://markojs.com/docs/reference/custom-tag An example `marko.json` file that specifies the export directory for custom tags within an installed package. This configuration tells Marko where to find the tags exposed by the library. ```json { "exports": "./dist/tags" } ``` -------------------------------- ### Inline CSS Modules with SCSS in Marko Source: https://markojs.com/docs/guide/styling Demonstrates using CSS Modules with the SCSS preprocessor by combining a Tag Variable and a file extension on the `
Hello
``` -------------------------------- ### Marko.js Layout Component Example Source: https://markojs.com/docs/marko-run/file-based-routing An example of a '+layout.marko' file, which serves as a wrapper component for nested layouts and pages. It defines an 'Input' interface and renders its content within a main HTML structure. ```marko /* +layout.marko */ export interface Input { content: Marko.Body; }

My Products

<${input.content}/> // render the page or layout here
``` -------------------------------- ### Marko: Controllable `` Tag Example Source: https://markojs.com/docs/reference/core-tag Demonstrates how to make the `` tag controllable using the `valueChange=` attribute. This allows for interception and transformation of state updates, enabling synchronization between parent and child components. ```marko ``` -------------------------------- ### Install and Use Marko Type Checker CLI Source: https://markojs.com/docs/introduction/installation Installs the `@marko/type-check` package as a development dependency for type checking Marko files. After installation, the `mtc` command can be used as a replacement for `tsc` to perform Marko-specific type checks. ```bash npm install -D @marko/type-check ``` ```bash mtc ``` -------------------------------- ### Inline CSS Modules in Marko Source: https://markojs.com/docs/guide/styling Explains how to use CSS Modules by adding a Tag Variable to the `
``` -------------------------------- ### Core Marko To-Do List Example Source: https://markojs.com/docs/explanation/nested-reactivity A foundational Marko component demonstrating a client-side To-Do list with add and delete functionality. It uses local state for managing the list of todos and next available ID. ```marko
``` -------------------------------- ### Using TypeScript Syntax in Marko Templates Source: https://markojs.com/docs/reference/typescript Illustrates how TypeScript expressions can be directly used within Marko templates for dynamic content rendering and type casting. It shows an example of casting an element to HTMLInputElement. ```marko ${(input.el as HTMLInputElement).value} ``` -------------------------------- ### Imported Styles in Marko Source: https://markojs.com/docs/guide/styling Shows how to import external CSS files into a Marko template using the `import` statement. Useful for sharing styles across multiple templates. Dependencies: Bundler configuration for CSS imports. ```css /* fancy.css */ .fancy { color: red; } ``` ```marko /* index.marko */ import "./fancy.css";
Hello!
``` -------------------------------- ### Marko Lifecycle Tag: Integrating with WorldMap API Source: https://markojs.com/docs/reference/core-tag This example demonstrates using the `` tag to initialize, update, and destroy a `WorldMap` instance. It shows how to manage the map's state (coordinates, zoom) based on component data and lifecycle events. ```marko client import { WorldMap } from "world-map-api";
onMount() { this.map = new WorldMap(container(), { latitude, longitude, zoom }); } onUpdate() { this.map.setCoords(latitude, longitude); this.map.setZoom(zoom); } onDestroy() { this.map.destroy(); } /> ``` -------------------------------- ### Marko Reactive Counter Example Source: https://markojs.com/docs/reference/reactivity Demonstrates a simple counter using Marko's reactivity. A '' tag initializes a 'count' variable to 0. A button increments 'count', and the button's text content, which displays '${count}', automatically updates to reflect the new value. ```marko ``` -------------------------------- ### Imported CSS Modules in Marko Source: https://markojs.com/docs/guide/styling Demonstrates importing CSS Modules files (typically named `*.module.css`) into Marko templates. Classes are accessed via an imported `styles` object. Dependencies: Bundler configured for CSS Modules. ```css /* something.module.css */ .fancy { color: red; } ``` ```marko /* index.marko */ import * as styles from "./something.module.css";
``` -------------------------------- ### Marko Environment Coordination: Tabs Component Source: https://markojs.com/docs/explanation/targeted-compilation This Marko tabs component example illustrates environment coordination. Server compilation renders initial HTML, while client compilation generates JavaScript only for interactive elements like tab switching and visibility updates. ```marko /* tabs.marko */ // Static

${input.title}

// Interactive
// Static content dependent on interactive state ``` -------------------------------- ### Marko Tag Type Arguments with Generics Source: https://markojs.com/docs/reference/typescript Shows how to explicitly provide type arguments when using a Marko tag that has generic type parameters. This example explicitly sets the type argument to 'number' for a '' tag. ```marko /* components/child.marko */ export interface Input { value: T; } ``` ```marko /* index.marko */ // number would be inferred in this case, but we can be explicit value=1 /> ``` -------------------------------- ### Enable TypeScript for Marko Sites/Web Apps with tsconfig.json Source: https://markojs.com/docs/reference/typescript To enable TypeScript support for Marko websites and web applications, a `tsconfig.json` file at the project root is the primary requirement. This configuration file guides the TypeScript compiler. ```plaintext src/ package.json tsconfig.json ``` -------------------------------- ### Configure tsconfig.json for Marko.js Source: https://markojs.com/docs/introduction/installation This JSON configuration file enables TypeScript support for a Marko.js project. It specifies compiler options such as module resolution, output directory, and strict type checking. Ensure this file is placed in the project's root directory. ```json { "include": ["src/**/*"], "compilerOptions": { "allowSyntheticDefaultImports": true, "lib": ["dom", "ESNext"], "module": "ESNext", "moduleResolution": "bundler", "noEmit": true, "noImplicitOverride": true, "noUnusedLocals": true, "outDir": "dist", "resolveJsonModule": true, "skipLibCheck": true, "strict": true, "target": "ESNext", "verbatimModuleSyntax": true } } ``` -------------------------------- ### Interactive Rating Component in Marko Source: https://markojs.com/docs/introduction/why-marko An example of an interactive rating component built with Marko. It uses `` for state (rating, hovering) and conditional logic (``, ``) to display the rating status dynamically. ```marko
0)> ${hovering} star${hovering > 1 ? 's' : ''} 0)> Rated ${rating} star${rating > 1 ? 's' : ''} Click to rate
``` -------------------------------- ### Auto-Discovered Styles for Marko Custom Tags Source: https://markojs.com/docs/guide/styling Illustrates how Marko automatically discovers and processes style files (e.g., `style.css`) located adjacent to custom tag files. Styles are imported and processed like inline styles. Input: `.css` file, Output: Global styles. ```css /* style.css */ .fancy { color: green; } ``` ```marko /* index.marko */
Hello!
``` -------------------------------- ### Typing Marko Input with JSDoc Source: https://markojs.com/docs/reference/typescript Demonstrates how to use JSDoc comments to define the types for a Marko component's input properties. This allows for type checking in JavaScript projects without a full TypeScript setup. ```marko // @ts-check /** * @typedef {{ * firstName: string, * lastName: string, * }} */
${firstName} ${lastName}
``` -------------------------------- ### Advanced Input Handling and Formatting in Marko Source: https://markojs.com/docs/reference/native-tag Presents several examples of input handling in Marko, including an uncontrolled input, a controlled input using the `:=` shorthand, and a controlled input with a custom `valueChange` handler that formats a credit card number by adding spaces. ```marko // uncontrolled - The browser owns the state // controlled - The `inputValue` tag variable owns the state // controlled - Modifications to `` are transformed ``` -------------------------------- ### Marko Tag Type Parameters with Generics Source: https://markojs.com/docs/reference/typescript Demonstrates how to define generic type parameters for a Marko tag, allowing the tag to work with different types. This example shows a '' tag with a type parameter 'T'. ```marko |value: T|> ... ``` -------------------------------- ### Manipulating Input with `valueChange` in Marko Source: https://markojs.com/docs/reference/native-tag Illustrates how `valueChange` can be used to intercept and transform input values before updating the component state. This example automatically converts all input characters to lowercase, showcasing its utility for input masking and validation. ```marko
${message}
``` -------------------------------- ### Marko Component Definition and Usage Source: https://markojs.com/docs/introduction/welcome-to-marko Defines a reusable 'hello' component with an input interface for a name and demonstrates its usage by passing a 'Marko' string to the name prop. This showcases Marko's component-based architecture for modularity. ```marko /* hello.marko */ export interface Input { name: string; }

Hello, ${input.name}

``` ```marko /* index.marko */ ``` -------------------------------- ### Unserializable Data Examples in Marko State Source: https://markojs.com/docs/explanation/serializable-state Illustrates common anti-patterns in Marko state management where custom class instances and DOM nodes are included, leading to serialization errors. These should be avoided for client-side state. ```marko // ❌ BAD: custom class instance in state // ❌ BAD: DOM nodes in state ``` -------------------------------- ### Marko: Syncing Input Value with State Source: https://markojs.com/docs/tutorial/components-and-reactivity Shows how to synchronize an input element's value with a tag variable using an `onInput` event handler. This makes the variable reactive to user input. ```marko
It's ${degF}°F
``` -------------------------------- ### Marko: Creating Computed Values with Source: https://markojs.com/docs/tutorial/components-and-reactivity Demonstrates how to create computed values based on existing tag variables using the `` tag. This allows for derived data, like Celsius conversion, to be displayed reactively. ```marko
${degF}°F ↔ ${degC.toFixed(1)}°C
``` -------------------------------- ### Marko HTML Streaming with Await for Asynchronous Content Source: https://markojs.com/docs/introduction/welcome-to-marko Demonstrates Marko's HTML streaming capabilities using the `` tag. A header is sent immediately, followed by a paragraph after a 500ms delay, showcasing how to send content to the client as it becomes available for improved perceived performance. ```marko
Sent immediately
setTimeout(res, 500))>

Sent after 500 milliseconds

``` -------------------------------- ### Marko: Accessing DOM Node Reference Source: https://markojs.com/docs/reference/native-tag Demonstrates how to get a reference to a native DOM node using the 'ref' attribute in Marko. The reference is only available client-side. Input is a native HTML 'div' tag. ```marko
``` -------------------------------- ### Marko State Management with Declarative UI Updates Source: https://markojs.com/docs/introduction/welcome-to-marko Illustrates state management in Marko using the `` tag to declare a reactive 'count' variable. Clicking the button increments the count, and the UI automatically updates to display the new value, demonstrating declarative UI updates. ```marko ``` -------------------------------- ### Marko Concise Syntax vs. HTML Source: https://markojs.com/docs/reference/concise-syntax Demonstrates the equivalence between Marko's concise syntax and standard HTML syntax for basic element and attribute declaration. Marko removes angle brackets and uses indentation for nesting. ```marko div class="thumbnail" img src="https://example.com/thumb.png" ``` ```html
``` -------------------------------- ### Basic HTML Structure in Marko Source: https://markojs.com/docs/introduction/why-marko Demonstrates how standard HTML is directly usable within Marko templates. This serves as the foundational syntax for Marko components. ```marko

My Products

  • Widget - $10
  • Gadget - $15
``` -------------------------------- ### Server-Side Rendering Logic in JavaScript Source: https://markojs.com/docs/introduction/why-marko Illustrates a Node.js Express route handler for rendering a product page on the server. It shows the typical steps: building component trees, fetching data, executing render logic, and generating HTML. This process repeats for every request, contributing to server-side runtime burden. ```javascript app.get('/product/:id', async (req, res) => { // 1. Parse and compile component tree structure const componentTree = buildServerComponents(); // 2. Resolve data dependencies const productData = await fetchProduct(req.params.id); const recommendations = await fetchRecommendations(productData.category); // 3. Execute render logic const html = framework.renderToString('ProductPage', { product: productData, recommendations: recommendations }); // 4. Generate final HTML with boilerplate res.send(wrapWithLayout(html)); }); ``` -------------------------------- ### Marko Component Encapsulation with State Source: https://markojs.com/docs/introduction/why-marko Demonstrates creating a reusable modal component in Marko, including local state management with `` and conditional rendering. It showcases basic component interaction and styling. ```marko
<${input.content}/>
``` -------------------------------- ### Using Controllable Counter with Parent State in Marko Source: https://markojs.com/docs/explanation/controllable-components Demonstrates how a parent component can manage the state of a controllable `` component using the `countChange` handler. This example shows both a controlled counter (with `countChange`) and an uncontrolled counter (without `countChange`). ```marko /* parent.marko */ // `parentCount` is the source of truth // This one holds its own state ``` -------------------------------- ### Uncontrolled Counter Component (Marko) Source: https://markojs.com/docs/explanation/controllable-components An example of an uncontrolled component in Marko where the component manages its own internal state. The 'count' state is defined and updated within the component itself using ``. This makes it easy to use but inaccessible to parent components. ```marko /* counter.marko */ ``` -------------------------------- ### Creating Reusable Components in Marko Source: https://markojs.com/docs/tutorial/fundamentals Marko supports componentization by allowing code to be placed in separate `.marko` files. These files can be used like HTML tags, promoting code reuse and organization. Components in the `tags/` directory are auto-discovered. ```marko /* tags/card.marko */

Alice

Designer

Joined 2023

``` ```marko

Our Team

``` -------------------------------- ### Conditional Rendering with Marko's and Tags Source: https://markojs.com/docs/tutorial/fundamentals Marko provides core tags for control flow. The `` and `` tags allow for conditional rendering of content based on boolean expressions, useful for managing UI states like product availability. ```marko /* tags/product.marko */

${input.name}

$${input.price}

``` ```marko ``` -------------------------------- ### Marko Local State for Disabled Delete Source: https://markojs.com/docs/explanation/nested-reactivity Extends the To-Do list example by introducing local state within each list item to track completion status ('done'). This prevents deleting items that are not yet completed, demonstrating local state management. ```marko
``` -------------------------------- ### Handling Asynchronous Operations with Marko Source: https://markojs.com/docs/introduction/why-marko Illustrates Marko's declarative approach to handling asynchronous operations using ``, ``, `<@placeholder>`, and `<@catch>` tags. This simplifies loading states and error handling for data fetching. ```marko

My Products

  • ${product.name} - $${product.price}
<@placeholder> Loading products... <@catch|error|> Failed to load: ${error.message} ``` -------------------------------- ### Extending Native HTML Button Tag in Marko Source: https://markojs.com/docs/reference/typescript Shows how to extend the types of native HTML tags within a Marko component. This example demonstrates extending the 'button' tag to include custom attributes like 'color' while inheriting standard button attributes. ```marko /* color-button.marko */ export interface Input extends Marko.HTML.Button { color: string; } ```