### d2 app scripts start Command Line Interface Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts/start.md Detailed documentation for the `d2 app scripts start` command, used to run a live-reloading development server for DHIS2 applications. It includes global options and specific parameters for configuring the server, proxy, and handling JSX files. ```sh d2 app scripts start --help ``` ```APIDOC d2-app-scripts start Start a development server running a DHIS2 app within the DHIS2 app-shell Global Options: -h, --help Show help [boolean] -v, --version Show version number [boolean] --verbose Enable verbose messages [boolean] --debug Enable debug messages [boolean] --quiet Enable quiet mode [boolean] --config Path to JSON config file Options: --cwd working directory to use (defaults to cwd) --force Force updating the app shell; normally, this is only done when a new version of @dhis2/cli-app-scripts is detected. Also passes the --force option to the Vite server to re-optimize dependencies [boolean] --port, -p The port to use when running the development server [number] [default: 3000] --proxy, -P The remote DHIS2 instance the proxy should point to [string] --proxyPort The port to use when running the proxy[number] [default: 8080] --host Exposes the server on the local network. Can optionally provide an address to use. [boolean or string] --allowJsxInJs Add Vite config to handle JSX in .js files. DEPRECATED: Will be removed in @dhis2/cli-app-scripts v13. Consider using the migration script `d2-app-scripts migrate js-to-jsx` to avoid needing this option [boolean] ``` -------------------------------- ### Example d2.config.js Configuration Source: https://github.com/dhis2/app-platform/blob/master/docs/config/d2-config-js-reference.md A JavaScript example demonstrating how to define the `d2.config.js` file for a DHIS2 application, including basic metadata, entry points, and custom data store/authority settings. ```javascript const config = { name: 'my-app', title: 'My Application', description: 'A simple application for doing DHIS2 things', type: 'app', entryPoints: { app: './src/App', }, dataStoreNamespace: 'my-custom-app-namespace', customAuthorities: ['my-app-analytics-user'], } module.exports = config ``` -------------------------------- ### Initialize New DHIS2 Application Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts.md These commands initialize a new DHIS2 application using `d2-app-scripts`. You can either use the globally installed `d2` CLI or run the script directly with `npx` without a global installation. ```Shell d2 app scripts init myapp ``` ```Shell npx @dhis2/cli-app-scripts init myapp ``` -------------------------------- ### Install @dhis2/cli-app-scripts Source: https://github.com/dhis2/app-platform/blob/master/cli/README.md This snippet demonstrates how to install the @dhis2/cli-app-scripts package as a development dependency using either Yarn or npm. This package provides essential build, start, and test scripts for DHIS2 applications. ```sh yarn add --dev @dhis2/cli-app-scripts # OR npm install --save-dev @dhis2/cli-app-scripts ``` -------------------------------- ### Install DHIS2 CLI Globally Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts.md This command installs the DHIS2 command-line interface globally using Yarn, enabling access to `d2` commands from any directory on your system. ```Shell yarn global add @dhis2/cli ``` -------------------------------- ### Start DHIS2 App with Proxy Source: https://github.com/dhis2/app-platform/blob/master/docs/proxy.md Demonstrates how to use the `d2-app-scripts start` command with the `--proxy` option to route requests to a remote DHIS2 instance, bypassing cross-site cookie issues. ```Shell d2-app-scripts start --proxy ``` -------------------------------- ### Install d2-app-scripts with Yarn Source: https://github.com/dhis2/app-platform/blob/master/docs/installation.md This command adds `@dhis2/cli-app-scripts` as a development dependency to your project using Yarn. This allows you to use the `d2-app-scripts` executable within your `package.json` scripts for various development tasks. ```sh yarn add --dev @dhis2/cli-app-scripts ``` -------------------------------- ### Install and Run DHIS2 App with Vite & React 18 Source: https://github.com/dhis2/app-platform/blob/master/docs/migration/v12.md Commands to update dependencies and start a DHIS2 application after migrating to platform v12, which uses Vite and React 18. The `--allowJsxInJs` flag is used for temporary compatibility. ```shell yarn add @dhis2/app-runtime @dhis2/ui -D @dhis2/cli-app-scripts npx yarn-deduplicate yarn.lock && yarn yarn start --allowJsxInJs ``` -------------------------------- ### Run DHIS2 App Development Scripts Source: https://github.com/dhis2/app-platform/blob/master/docs/bootstrapping.md Shows the common `yarn` commands for testing, starting a development server, and building a production version of the bootstrapped DHIS2 application. These scripts are provided by `@dhis2/cli-app-scripts` and simplify the development workflow. ```sh yarn test ``` ```sh yarn start ``` ```sh yarn build ``` -------------------------------- ### Serving Custom Static Files from Public Directory (DHIS2 App Platform) Source: https://github.com/dhis2/app-platform/blob/master/docs/usage/static-files.md This shell command sequence illustrates how to create a custom static file (`test.txt`) within the `./public` directory of a DHIS2 application. When the application is started (`yarn start`), this file becomes accessible via a direct URL relative to the application's root, such as `http://localhost:3000/test.txt`. ```sh > echo "THIS IS A TEST" > ./public/test.txt\n> yarn start ``` -------------------------------- ### DHIS2 App Platform Environment Variables Reference Source: https://github.com/dhis2/app-platform/blob/master/docs/config/environment.md Detailed reference for configuration environment variables used by the DHIS2 app-platform `start` and `build` commands, including their types, usage, and specific warnings or deprecation notices. ```APIDOC Variable: PORT Type: Number Commands: start Description: Specify the Port to use when running the development server. Can also be specified with the --port flag on the command-line Variable: PUBLIC_URL Type: String Commands: start, build Description: ADVANCED USERS ONLY Specify the contextualized path at which the application will be deployed. By default this will be ., but it can be overridden manually in rare cases. Variable: DHIS2_BASE_URL Type: String Commands: start, build Description: ADVANCED USERS ONLY Specify the base URL of the DHIS2 server to bake into the production artifact. In almost all cases the defaults are preferred, as they are pre-configured to work as installed DHIS2 applications. Variable: DHIS2_API_VERSION Type: Number Commands: start, build Description: DEPRECATED Specify the version of DHIS2 API to use. As of App Platform v5.3, the shell will automatically detect the version of the DHIS2 server instance and set the API version to the latest version available. This configuration option SHOULD NOT BE USED and will be deprecated soon ``` -------------------------------- ### Publishing a DHIS2 App Bundle to App Hub Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts/publish.md This example demonstrates how to publish a built DHIS2 application bundle to the App Hub. It shows setting the `D2_APP_HUB_API_KEY` environment variable for authentication and specifying minimum and maximum DHIS2 version compatibility for the uploaded app. ```sh > d2 app scripts publish > export D2_APP_HUB_API_KEY=xyz > d2 app scripts publish --minVersion 2.34 --maxVersion 2.36 ``` -------------------------------- ### Running DHIS2 Application in Development Mode Source: https://github.com/dhis2/app-platform/blob/master/docs/troubleshooting.md Explains how to start a DHIS2 application in development mode and configure server connections. It also covers common server URLs and references to local development environments. ```Shell yarn start ``` ```Shell d2 cluster ``` -------------------------------- ### Install d2-app-scripts as Development Dependency Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts.md This command adds `d2-app-scripts` as a development dependency to your project's `package.json` using Yarn. This is the common method for including it in an existing application. ```Shell yarn add --dev @dhis2/cli-app-scripts ``` -------------------------------- ### Run DHIS2 App in Development Mode with Yarn Source: https://github.com/dhis2/app-platform/blob/master/cli/config/templates/common/README.md Starts the DHIS2 application in development mode, making it accessible via http://localhost:3000. The page reloads automatically on edits, and lint errors are displayed in the console. ```Shell yarn start ``` -------------------------------- ### Using Jest Fake Timers with React Testing Library and user-event Source: https://github.com/dhis2/app-platform/blob/master/docs/migration/v12.md This example demonstrates how to set up Jest's fake timers (`jest.useFakeTimers`) and integrate them with `user-event.setup({ advanceTimers: jest.advanceTimersByTime })` for testing components with time-dependent behavior in `@testing-library/react`. ```javascript describe('', () => { beforeEach(() => { jest.useFakeTimers() }) afterEach(() => { // ... cleanup }) it('shows a loading indicator when submitting a comment change', async () => { // ... setup const { findByRole } = render() const editButton = await findByRole('button', { name: 'Edit comment' }) const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime, }) await user.click(editButton) // ... assertions const btnSaveComment = await findByRole('button', { name: 'Save comment', }) await user.click(btnSaveComment) await findByRole('progressbar') }) }) ``` -------------------------------- ### Example of Named Import in JavaScript Source: https://github.com/dhis2/app-platform/blob/master/docs/troubleshooting.md A typical JavaScript import statement that can lead to a named import compilation error if the module is not correctly exported. ```JavaScript import { BrowserRouter } from 'react-router-dom' ``` -------------------------------- ### Named Import Compilation Error Message Source: https://github.com/dhis2/app-platform/blob/master/docs/troubleshooting.md An example of the error message encountered when a named import fails to resolve, indicating that the module is not exported by the specified path. ```Text [ERROR] Error: 'BrowserRouter' is not exported by node_modules/react-router-dom/index.js [ERROR] At **src/App.js:4:9** ``` -------------------------------- ### Vite JSX in JS Error Message Source: https://github.com/dhis2/app-platform/blob/master/docs/migration/v12.md Example error message displayed by Vite when JSX syntax is used in `.js` files without the `--allowJsxInJs` flag or proper file extensions, indicating that the JSX extension is not enabled by default. ```shell ✘ [ERROR] The JSX syntax extension is not currently enabled ``` -------------------------------- ### Importing External CSS Files in DHIS2 React Applications Source: https://github.com/dhis2/app-platform/blob/master/docs/usage/css.md The DHIS2 Application Platform supports importing standard .css files. This example shows how to define CSS rules in App.css and import them into a React component (App.js), applying styles globally to matching HTML elements. ```css /* App.css */ p { color: red; } ``` ```js /* App.js */ import React from 'react' import './App.css' export default () => (

All p tags will be red!

) ``` -------------------------------- ### Modularizing styled-jsx Styles in Separate Files for React Components Source: https://github.com/dhis2/app-platform/blob/master/docs/usage/css.md For better organization, styled-jsx styles can be defined in separate JavaScript files and imported into React components. This example demonstrates creating App.styles.js to define styles and then applying them to a specific element in App.js using a class selector. ```js /* App.styles.js */ import css from 'styled-jsx/css' // We target .root here, which allows us to explicitly target only the container div export default css` .root { position: absolute; top: 48px; bottom: 0; left: 0; right: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: 1rem; } ` ``` ```js /* App.js */ import React from 'react' import styles from './App.styles' export default () => (
{/* ONLY this div (with the .root class and {/* This div does not have the .root class, so it will not be styled by the above CSS rule! */}
UNSTYLED
) ``` -------------------------------- ### Use Stable Reference for Default Array/Object Props in React Functional Components Source: https://github.com/dhis2/app-platform/blob/master/docs/migration/v12.md This example demonstrates how to use a stable reference (an empty array `[]`) for default prop values in React functional components to prevent unintentional re-renders of `useEffect` and `useMemo` hooks, which can occur if default arrays/objects are computed on each render. ```javascript const arr = [] const MyComponent = ({ options = arr }) => { /* ... */ } ``` -------------------------------- ### d2 app scripts init Command Line Interface Help Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts/init.md Displays the help output for the `d2 app scripts init` command, detailing its usage, global options, and specific options for application initialization. Options include `--cwd` for working directory, `--force` to overwrite, `--lib` to create a library, and `--typeScript` for TypeScript templates. ```sh > d2 app scripts init --help d2 app scripts init Setup an app Global Options: -h, --help Show help [boolean] -v, --version Show version number [boolean] --verbose Enable verbose messages [boolean] --debug Enable debug messages [boolean] --quiet Enable quiet mode [boolean] --config Path to JSON config file Options: --cwd working directory to use (defaults to cwd) --force Overwrite existing files and configurations [boolean] [default: false] --lib Create a library [boolean] [default: false] --typeScript, --typescript, --ts Use TypeScript template [boolean] [default: false] ``` -------------------------------- ### Initialize DHIS2 App and Inspect Structure Source: https://github.com/dhis2/app-platform/blob/master/docs/bootstrapping.md Demonstrates how to use the `d2 app scripts init` command to create a new DHIS2 application, navigate into its directory, and view the generated file structure using `tree`. It also shows the minimal `package.json` dependencies for a bootstrapped DHIS2 app. ```sh d2 app scripts init my-test-app cd my-test-app ``` ```text . ├── d2.config.js ├── package.json └── src ├── App.js └── App.test.js ``` ```json { "name": "my-test-app", "version": "1.0.0", "description": "", "license": "BSD-3-Clause", "private": true, "scripts": { "build": "d2-app-scripts build", "start": "d2-app-scripts start", "test": "d2-app-scripts test" }, "devDependencies": { "@dhis2/cli-app-scripts": "1.4.1" }, "dependencies": { "@dhis2/app-runtime": "^2.0.4" } } ``` -------------------------------- ### Display help for d2 app scripts pack command Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts/pack.md This command-line interface (CLI) snippet shows the help output for `d2 app scripts pack`. It details how to create a .zip archive of a built application, specifying the source directory, destination, filename, app name, and app version. Note that this command is currently unsupported for libraries. ```sh d2 app scripts pack --help d2-app-scripts pack [source] Create a .zip archive of a built application Positionals: source The source directory to pack relative to cwd. [string] [default: ./build/app] Global Options: -h, --help Show help [boolean] -v, --version Show version number [boolean] --verbose Enable verbose messages [boolean] --debug Enable debug messages [boolean] --quiet Enable quiet mode [boolean] --config Path to JSON config file Options: --cwd working directory to use (defaults to cwd) --destination, --dest, -d Directory to save the packed archive to. [string] [default: ./build/bundle] --filename Override the filename of the archive. [string] [default: {app-name}-{version}.zip] --app-name The name of the app to replace in filename [string] [default: ${config.name}] --app-version The version of the app to replace in filename [string] [default: ${config.version}] ``` -------------------------------- ### d2-app-scripts migrate js-to-jsx Command Help Output Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts/migrate/js-to-jsx.md This output provides the comprehensive help documentation for the `d2-app-scripts migrate js-to-jsx` command. It lists all available global and command-specific options, including `--skipUpdatingImportsWithoutExtension` and `--globString`, along with their descriptions, types, and default values. This is essential for understanding the full capabilities and configuration of the migration script. ```sh > d2-app-scripts migrate js-to-jsx --help d2-app-scripts migrate js-to-jsx Renames .js files that include JSX to .jsx. Also handles file imports and d2.config.js Global Options: -h, --help Show help [boolean] -v, --version Show version number [boolean] --verbose Enable verbose messages [boolean] --debug Enable debug messages [boolean] --quiet Enable quiet mode [boolean] --config Path to JSON config file Options: --cwd working directory to use (defaults to cwd) --skipUpdatingImportsWithoutExtension Normally, this script will update `import './App'` to `import './App.jsx'`. Use this flag to skip adding the extension in this case. Imports that already end with .js will still be updated to .jsx [boolean] [default: false] --globString Glob string to use for finding files to parse, rename, and update imports. It will be manipulated by the script, so it must end with .js, and make sure to use quotes around this argument to keep it a string [string] [default: "src/**/*.js"] ``` -------------------------------- ### d2 app scripts build CLI Options Reference Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts/build.md Detailed reference for the `d2 app scripts build` command, outlining all available global and build-specific command-line options, their types, default values, and descriptions for configuring DHIS2 app builds. ```APIDOC d2-app-scripts build Build a production app bundle for use with the DHIS2 app-shell Global Options: -h, --help Show help [boolean] -v, --version Show version number [boolean] --verbose Enable verbose messages [boolean] --debug Enable debug messages [boolean] --quiet Enable quiet mode [boolean] --config Path to JSON config file Options: --cwd working directory to use (defaults to cwd) --mode Specify the target build environment [choices: \"development\", \"production\"] [default: production] --dev Build in development mode [boolean] --verify Validate package before building [boolean] [default: true] --watch Watch source files for changes [boolean] [default: false] --standalone Build in standalone mode (overrides the d2.config.js setting) [boolean] --allowJsxInJs Add Vite config to handle JSX in .js files. DEPRECATED: Will be removed in @dhis2/cli-app-scripts v13. Consider using the migration script `d2-app-scripts migrate js-to-jsx` to avoid needing this option [boolean] ``` -------------------------------- ### d2 app scripts publish Command Line Options Reference Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts/publish.md This section provides a detailed reference for all command-line options available with `d2 app scripts publish`. It includes global options like `--help`, `--version`, and `--verbose`, as well as specific options for authentication (`--token`), publishing channels (`--channel`), App Hub base URL (`--baseUrl`), DHIS2 version compatibility (`--minDHIS2Version`, `--maxDHIS2Version`), file uploads (`--file`, `--file-version`, `--appId`), and upload timeout (`--timeout`). Each option's type and default value are also listed. ```APIDOC d2-app-scripts publish Deploy the built application to a specific DHIS2 instance Global Options: -h, --help Show help [boolean] -v, --version Show version number [boolean] --verbose Enable verbose messages [boolean] --debug Enable debug messages [boolean] --quiet Enable quiet mode [boolean] --config Path to JSON config file Options: --cwd working directory to use (defaults to cwd) --token, --app-hub-token, -k The API token to use for authentication [string] --channel, -c The channel to publish the app-version to [default: "stable"] --baseUrl, -b The base-url of the App Hub instance [default: "https://apps.dhis2.org"] --minDHIS2Version The minimum version of DHIS2 the app supports [string] --maxDHIS2Version The maximum version of DHIS2 the app supports [string] --appId Only used with --file option. The App Hub ID for the App to publish to [string] --file Path to the file to upload. This skips automatic resolution of the built app and uses this file-path to upload --file-version Only used with --file option. The semantic version of the app uploaded [string] --timeout The timeout (in seconds) for uploading the app bundle [default: 300] ``` -------------------------------- ### d2 app scripts deploy CLI Help and Options Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts/deploy.md This snippet shows the command-line help output for 'd2 app scripts deploy', detailing its usage, positional arguments, global options (help, version, verbose, debug, quiet, config), and specific options (cwd, username, timeout) for deploying a DHIS2 application. ```sh d2 app scripts deploy --help d2-app-scripts deploy [baseUrl] Deploy the built application to a specific DHIS2 instance Global Options: -h, --help Show help [boolean] -v, --version Show version number [boolean] --verbose Enable verbose messages [boolean] --debug Enable debug messages [boolean] --quiet Enable quiet mode [boolean] --config Path to JSON config file Options: --cwd working directory to use (defaults to cwd) --username, -u The username for authenticating with the DHIS2 instance --timeout The timeout (in seconds) for uploading the app bundle [default: 300] ``` -------------------------------- ### Build DHIS2 App for Production with Yarn Source: https://github.com/dhis2/app-platform/blob/master/cli/config/templates/common/README.md Builds the DHIS2 application for production, optimizing React and bundling assets into the `build` folder. A minified, hashed build is created, and a deployable `.zip` file is generated in `build/bundle`. ```Shell yarn build ``` -------------------------------- ### Run d2-app-scripts to migrate JS to JSX Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts/migrate/js-to-jsx.md Demonstrates the basic command to execute the `d2-app-scripts migrate js-to-jsx` utility. This command should be run from the root directory of your project to initiate the file renaming and import updating process. ```sh yarn d2-app-scripts migrate js-to-jsx ``` -------------------------------- ### Deploy Built DHIS2 App to Instance with Yarn Source: https://github.com/dhis2/app-platform/blob/master/cli/config/templates/common/README.md Deploys the previously built DHIS2 application from the `build` folder to a running DHIS2 instance. This command requires `yarn build` to be executed first and will prompt for the server URL, username, and password of a DHIS2 user with App Management authority. ```Shell yarn deploy ``` -------------------------------- ### CLI: d2 app scripts test command help and options Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts/test.md Displays the help message and available options for the `d2 app scripts test` command, including global configurations and specific options for test execution like snapshot updates, coverage collection, and watch modes. ```APIDOC d2-app-scripts test [testRegex] Run application unit tests Global Options: -h, --help Show help [boolean] -v, --version Show version number [boolean] --verbose Enable verbose messages [boolean] --debug Enable debug messages [boolean] --quiet Enable quiet mode [boolean] --config Path to JSON config file Options: --cwd working directory to use (defaults to cwd) --updateSnapshot Update jest snapshots [boolean] [default: false] --coverage Collect test coverage [boolean] [default: false] --watch, -w Watch modified source files for changes [boolean] [default: false] --watchAll Watch all source files for changes[boolean] [default: false] --jestConfig Path to a jest config file ``` -------------------------------- ### Building DHIS2 Libraries with d2-app-scripts Source: https://github.com/dhis2/app-platform/blob/master/docs/troubleshooting.md Demonstrates how to use `d2-app-scripts build` for compiling DHIS2 libraries, including an option to skip package validation. This command is crucial for managing entry points and tree-shaking. ```Shell d2-app-scripts build ``` ```Shell d2-app-scripts build --no-verify ``` -------------------------------- ### Uploading a Non-Platform DHIS2 App Bundle Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts/publish.md This snippet illustrates how to upload an app version that is not a standard DHIS2 platform app. It uses the `--file` option to specify the path to the bundled `.zip` file and includes options for the file version, minimum DHIS2 version, and the App Hub ID. ```sh > d2 app scripts publish --file build/simple-app.zip --file-version 1.0.1 --minDHIS2Version 2.34 --appId ``` -------------------------------- ### Run Tests for DHIS2 App with Yarn Source: https://github.com/dhis2/app-platform/blob/master/cli/config/templates/common/README.md Launches the test runner to execute all available tests found within the `/src` directory of the DHIS2 application. ```Shell yarn test ``` -------------------------------- ### Initialize DHIS2 App with TypeScript Template Source: https://github.com/dhis2/app-platform/blob/master/docs/migration/v12.md Command to bootstrap a new DHIS2 application using a TypeScript template, supported in platform v12. ```shell d2-app-scripts init --typescript my-app ``` -------------------------------- ### Deploy DHIS2 App with Credentials via CLI Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts/deploy.md This snippet demonstrates how to build a DHIS2 application, set the password using an environment variable, and then deploy the application to a specified DHIS2 instance using the 'd2 app scripts deploy' command with a username, bypassing interactive prompts. ```sh d2 app scripts build export D2_PASSWORD=xyz d2 app scripts deploy https://play.dhis2.org/dev --username admin ``` -------------------------------- ### Configure DHIS2 App with d2.config.js and TypeScript Hints Source: https://github.com/dhis2/app-platform/blob/master/docs/config/d2-config-js-reference.md This JavaScript snippet demonstrates how to define the `d2.config.js` configuration file for a DHIS2 application. It includes a JSDoc type annotation to enable TypeScript and Intellisense hints for the configuration object, leveraging the `D2Config` type from `@dhis2/cli-app-scripts`. ```javascript // d2.config.js /** @type {import('@dhis2/cli-app-scripts').D2Config} */ const config = { type: 'app', ... } module.exports = config ``` -------------------------------- ### Configuring package.json for DHIS2 Library Exports Source: https://github.com/dhis2/app-platform/blob/master/docs/troubleshooting.md Illustrates the necessary `package.json` fields (`main`, `module`, `exports`, `sideEffects`) for DHIS2 libraries after upgrading to `@dhis2/cli-app-scripts` v5.6. Proper configuration ensures correct module resolution and tree-shaking. ```JSON { "main": "build/cjs/index.js", "module": "build/es/index.js", "exports": { ".": { "import": "./build/es/index.js", "require": "./build/cjs/index.js" } }, "sideEffects": [ "./build/es/locales/index.js", "./build/cjs/locales/index.js" ] } ``` -------------------------------- ### DHIS2 App-Platform Configuration Properties Source: https://github.com/dhis2/app-platform/blob/master/docs/config/d2-config-js-reference.md Defines the various configuration properties available for DHIS2 applications and libraries. Each property includes its data type, default value, and a detailed explanation of its usage and impact on the application's behavior or manifest. ```APIDOC Property: type Type: string Default: app Description: Either app, login_app or lib Property: name Type: string Default: pkg.name Description: A short, machine-readable unique name for this app Property: title Type: string Default: config.name Description: The human-readable application title, which will appear in the HeaderBar Property: direction Type: 'ltr', 'rtl', or 'auto' Default: 'ltr' Description: Sets the dir HTML attribute on the document of the app. If set to 'auto', the direction will be inferred from the current user's UI locale setting. The header bar will always be considered 'auto' and is unaffected by this setting. Property: id Type: string Default: Description: The ID of the app on the App Hub (https://apps.dhis2.org/). Used when publishing the app to the App Hub with d2 app scripts publish (../scripts/publish). See this guide (https://developers.dhis2.org/docs/guides/publish-apphub/) to learn how to set up continuous delivery. Property: description Type: string Default: pkg.description Description: A full-length description of the application Property: author Type: string or object Default: pkg.author Description: The name of the developer to include in the DHIS2 manifest, following package.json author field syntax (https://docs.npmjs.com/cli/v8/configuring-npm/package-json#people-fields-author-contributors). Property: entryPoints.app Type: string Default: ./src/App Description: The path to the application entrypoint (not used for libraries) Property: entryPoints.plugin Type: string Default: Description: The path to the application's plugin entrypoint (not used for libraries) Property: entryPoints.lib Type: string or object Default: ./src/index Description: The path to the library entrypoint(s) (not used for applications). Supports conditional exports (https://nodejs.org/dist/latest-v16.x/docs/api/packages.html#packages_conditional_exports) ``` -------------------------------- ### De-duplicate Singleton Dependencies with yarn-deduplicate Source: https://github.com/dhis2/app-platform/blob/master/docs/usage/dependencies.md This command demonstrates how to use `npx yarn-deduplicate` to ensure only a single copy of specified common DHIS2 application dependencies exists in the application bundle. This practice reduces the final bundle size, improves network performance, and prevents potential conflicts arising from multiple versions of the same library. It targets key libraries like React, React DOM, DHIS2 App Runtime, DHIS2 UI Core, DHIS2 D2 I18n, and Styled JSX. ```sh npx yarn-deduplicate --packages react,react-dom,@dhis2/app-runtime,@dhis2/ui-core,@dhis2/d2-i18n,styled-jsx ``` -------------------------------- ### Migrate React Testing Library `userEvent` to Async Source: https://github.com/dhis2/app-platform/blob/master/docs/migration/v12.md This diff shows the migration of `userEvent` interactions to be asynchronous, requiring `await` for `userEvent.click()` and replacing `fireEvent.click()` with `userEvent.click()`. It also demonstrates importing `userEvent`. ```diff + import userEvent from '@testing-library/user-event' - it('should allow re-running validation', () => { + // Make the function async: + it('should allow re-running validation', async () => { // ... - userEvent.click(getByText('Run validation again')) - // Or this other form: - fireEvent.click(getByText('Run validation again')) + // Now that it's asynchronous, await the event: + await userEvent.click(getByText('Run validation again')) await findByText('2 medium priority alerts') expect(queryByText('There was a problem running validation')).toBeNull() }) ``` -------------------------------- ### DHIS2 App Configuration Properties Source: https://github.com/dhis2/app-platform/blob/master/docs/config/d2-config-js-reference.md Defines the available properties for configuring a DHIS2 application, including their types, default values, and descriptions. These properties are typically set in the `d2.config.js` file. ```APIDOC d2.config.js Properties: skipPluginLogic: boolean = false Description: By default, plugin entry points will be wrapped with logic to allow the passing of properties and resizing between the parent app and the child plugin. This logic will allow users to use the plugin inside an app when wrapped in component from app-runtime. If set to true, this logic will not be loaded. pluginType: string Description: Gets added to the the `plugin_type` field for this app in the `/api/apps` response -- an example is `pluginType: 'DASHBOARD'` for a plugin meant to be consumed by the Dashboard app. Must be contain only characters from the set A-Z (uppercase), 0-9, `-` and `_`; i.e., it's tested against the regex `/^[A-Z0-9-_]+$/`. dataStoreNamespace: string Description: The DataStore and UserDataStore namespace to reserve for this application. The reserved namespace **must** be suitably unique, as other apps will fail to install if they attempt to reserve the same namespace - see the webapp manifest docs. additionalNamespaces: Array Description: An array of additional datastore namespaces that should be associated with the app. For each, the user can specify the authorities required to read/write. See more in the Additional datastore namespaces section. customAuthorities: Array Description: An array of custom authorities to create when installing the app, these do not provide security protections in the DHIS2 REST API but can be assigned to user roles and used to modify the interface displayed to a user - see the webapp manifest docs. minDHIS2Version: string Description: The minimum DHIS2 version the App supports (eg. '2.35'). Required when uploading an app to the App Hub. The app's major version in the app's package.json needs to be increased when changing this property. maxDHIS2Version: string Description: The maximum DHIS2 version the App supports. coreApp: boolean = false Description: If true, build an app artifact to be included as a root-level core application. standalone: boolean = false Description: If true, do NOT include a static BaseURL in the production app artifact. This includes the `Server` field in the login dialog, which is usually hidden and pre-configured in production. pwa: object Description: Opts into and configures PWA settings for this app. Read more about the options in the PWA docs. ``` -------------------------------- ### JavaScript Client-Side Redirection to DHIS2 Developer Portal Source: https://github.com/dhis2/app-platform/blob/master/docs/index.html This JavaScript snippet handles client-side redirection. It extracts a hash value from the current URL (skipping the first two characters, likely '##'), constructs a new URL pointing to the DHIS2 Developer Portal's app-platform section using a template literal, and then redirects the browser to this new URL. This is typically used for deep linking within the documentation or handling legacy URL structures. ```JavaScript const hash = window.location.hash.substring(2) const newUrl = `https://developers.dhis2.org/docs/app-platform/${hash}` document.getElementById('url').href = newUrl window.location.href = newUrl ``` -------------------------------- ### Configure Additional Datastore Namespaces with Access Authorities Source: https://github.com/dhis2/app-platform/blob/master/docs/config/d2-config-js-reference.md This JavaScript configuration demonstrates how to declare additional datastore namespaces for a DHIS2 app. Each namespace object specifies a name and can define access control using `authorities` (for both read/write), `readAuthorities` (for read-only), or `writeAuthorities` (for write-only). If `authorities` is combined with specific read/write lists, the entries are added as a union. ```JavaScript const config = { // ... additionalNamespaces: [ { namespace: 'extra1', authorities: ['M_extra1'] }, { namespace: 'extra2', readAuthorities: ['M_extra2read'] }, { namespace: 'extra3', writeAuthorities: ['M_extra3write'] }, { namespace: 'extra4', authorities: ['M_extra4readwrite'], writeAuthorities: ['M_extra4write'] } ] } ``` -------------------------------- ### Importing Image Files in JavaScript (DHIS2 App Platform) Source: https://github.com/dhis2/app-platform/blob/master/docs/usage/static-files.md This JavaScript snippet demonstrates how to import an image file (`.png`) directly into a React component. The DHIS2 Application Platform automatically handles the asset, either embedding it in the bundle or serving it as an external file, and provides a URL for the `src` attribute of an `` tag. ```js import myImage from './myimage.png'\n\nfunction MyImage() {\n return \n} ``` -------------------------------- ### Upgrading @dhis2/cli-app-scripts Package Source: https://github.com/dhis2/app-platform/blob/master/docs/troubleshooting.md Command to upgrade the `@dhis2/cli-app-scripts` package to the latest version, which resolves common compilation issues like named import errors. ```Shell yarn add @dhis2/cli-app-scripts ``` -------------------------------- ### Migrating renderHook from react-hooks to react-testing-library Source: https://github.com/dhis2/app-platform/blob/master/docs/migration/v12.md This snippet demonstrates the updated import path for `renderHook` from `@testing-library/react` and how to replace `waitForNextUpdate` with `waitFor` for handling asynchronous operations in hook tests. ```javascript import { renderHook, waitFor } from '@testing-library/react' import React from 'react' import { useRootOrgData } from './use-root-org-data.js' it('should provide the org unit data', async () => { const { result } = renderHook(() => useRootOrgData(['A0000000000']), { wrapper, }) await waitFor(() => {}) // ... }) ``` -------------------------------- ### API: d2-app-scripts migrate js-to-jsx --globString option Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts/migrate/js-to-jsx.md Documents the `--globString` command-line option for `d2-app-scripts migrate js-to-jsx`. This option allows users to specify a custom glob pattern, overriding the default `src/**/*.js`, to control which files are crawled for migration. ```APIDOC --globString: Type: string Description: Specifies a custom glob pattern for crawling files to migrate. Imports will only be updated within the scope of this glob. Contents of `node_modules` directories are always ignored. Default: "src/**/*.js" Usage Example: yarn d2-app-scripts migrate js-to-jsx --globString "src/components/**/*.js" Note: Always use quotes around the argument to prevent shell interpretation. ``` -------------------------------- ### PWA Caching Configuration Options Source: https://github.com/dhis2/app-platform/blob/master/docs/pwa/pwa.md Defines the available configuration properties for managing PWA caching behavior, including deprecated options and their replacements, URL pattern matching for caching exclusions, and methods for extending the precache manifest. ```APIDOC pwa.caching.omitExternalRequests: Type: Boolean Description: Deprecated; superceded by "omitExternalRequestsFromAppShell". The new option takes precedence. pwa.caching.patternsToOmitFromAppShell: Type: Array of RegExps or Strings Description: A list of URL patterns to omit from the default app shell caching strategies. Strings will be converted to RegExes using "new RegExp(str)" (with their special characters escaped) to test URLs. If a URL matches one of these patterns, that request will not be cached as part of the app shell. Note that this setting does not affect the recording mode. When choosing these URL filters, note that it is better to _cache too many things_ than to risk _not caching an important part of the app shell_ which could break the offline functionality of the app, so choose your filter patterns accordingly. pwa.caching.patternsToOmitFromCacheableSections: Type: Array of RegExps or Strings Description: Similar to the above setting, except this is a list of URL patterns to omit from _cacheable (recorded) sections_. Requests with URLs that are filtered out from cacheable sections can still be cached in the app shell cache, unless they are filtered out from the app shell as well using the setting above. When choosing these URL filters, note that it is better to _cache too many things_ than to risk _not caching an important part of the section_ which could break the offline functionality of the section, so choose your filter patterns accordingly. pwa.caching.patternsToOmit: Type: Array of RegExps or Strings Description: Deprecated; superceded by "patternsToOmitFromAppShell". The new option takes precedence. pwa.caching.additionalManifestEntries: Type: Array of Objects with signature "{ revision: String, url: String }" Description: A list of files that can be added to the precache manifest. Note that the service worker uses Workbox to precache all static assets that end up in the ‘build’ folder after the CRA compilation and build step during the d2-app-scripts build process. The format of this list must match the [required format for Workbox precache manifests](https://developers.google.com/web/tools/workbox/modules/workbox-precaching#explanation_of_the_precache_list), i.e. it must include a revision hash to inform when that file needs to be updated in the precache. ``` -------------------------------- ### Run d2-app-scripts js-to-jsx with skipUpdatingImportsWithoutExtension Source: https://github.com/dhis2/app-platform/blob/master/docs/scripts/migrate/js-to-jsx.md This command demonstrates how to execute the `d2-app-scripts migrate js-to-jsx` script while utilizing the `--skipUpdatingImportsWithoutExtension` flag. This flag prevents the script from automatically appending `.jsx` extensions to imports that do not already specify an extension, which can be useful for projects using TypeScript or specific import resolution rules. ```sh yarn d2-app-scripts migrate js-to-jsx --skipUpdatingImportsWithoutExtension ``` -------------------------------- ### Run JS to JSX Migration Codemod Source: https://github.com/dhis2/app-platform/blob/master/docs/migration/v12.md This shell command executes a codemod script to migrate JavaScript files with JSX syntax to `.jsx` extensions and updates corresponding import paths within the project. ```shell yarn d2-app-scripts migrate js-to-jsx ``` -------------------------------- ### PWA Recording Mode and Cacheable Sections Source: https://github.com/dhis2/app-platform/blob/master/docs/pwa/pwa.md The App Platform includes 'Cacheable Sections' and 'recording mode' to support on-demand caching of specific app parts, such as individual dashboards. This allows users to cache content only when requested, track its status, and ensures that large, non-essential data isn't cached by default, while still enabling offline access. ```APIDOC Recording Mode and Cacheable Sections: Purpose: To support caching individual app sections (e.g., dashboards) on user request, rather than by default. Characteristics: - Allows selective caching of content not cached by default. - Enables tracking of caching status (cached/not cached, last updated). Mechanism: - A Cacheable Section can reload a component. - Instructs the service worker to listen to and cache all relevant data requested for that component. Related Configuration: - `patternsToOmit` option (from `d2.config.js` table): Used to omit requests to particular URLs from default caching behavior, allowing them to be handled by Cacheable Sections. ``` -------------------------------- ### React API for CacheableSection Component and Hook Source: https://github.com/dhis2/app-platform/blob/master/docs/pwa/pwa.md Describes the usage of the `` React component and the `useCacheableSection` hook for enabling offline caching of specific app sections. The component identifies the section by an ID, and the hook provides programmatic control over the caching process for that section. ```APIDOC CacheableSection Component: Description: A React component to wrap sections of an app that should be made available for offline use. Props: id: string - A unique identifier for the cacheable section. Required. Usage: {/* Content to be cached for offline access */} useCacheableSection Hook: Description: A React hook to access controls and trigger caching 'recording' for a specific CacheableSection. Parameters: id: string - The ID of the CacheableSection component to interact with. Required. Returns: An object providing methods to control the caching state and trigger recording for the specified section. ``` -------------------------------- ### Accessing DHIS2 Environment Variables Source: https://github.com/dhis2/app-platform/blob/master/docs/migration/v12.md Illustrates the change in accessing environment variables after migrating from Create React App. Previously, variables required a `REACT_APP_` prefix, but now they are directly accessible via `DHIS2_` prefix. Both forms are available for backward compatibility in the current version but the `REACT_APP_` prefix is deprecated. ```JavaScript console.log(process.env.REACT_APP_DHIS2_MY_VAR); console.log(process.env.DHIS2_MY_VAR); ``` -------------------------------- ### Accessing Environment Variables with Vite's import.meta.env Source: https://github.com/dhis2/app-platform/blob/master/docs/migration/v12.md Demonstrates how Vite exposes environment variables via `import.meta.env`. The App Platform configures `DHIS2_` prefixed variables to be available here, although `process.env` is still emphasized for broader compatibility. ```JavaScript console.log(import.meta.env.DHIS2_MY_VAR); ``` -------------------------------- ### PWA Configuration Object in d2.config.js Source: https://github.com/dhis2/app-platform/blob/master/docs/pwa/pwa.md Defines the structure and properties for configuring Progressive Web App (PWA) features within the `d2.config.js` file, including service worker registration and caching strategies. ```APIDOC pwa: Object description: Top-level object for PWA configuration. properties: enabled: Boolean description: If true, enables registration of a service worker to perform offline caching in both development and production builds. This is required to enable Cacheable Sections. In development mode, the service worker uses different caching strategies to facilitate development. If false or not set, any service worker registered in this scope will be unregistered. caching: Object description: Contains several properties to configure offline caching by the service worker. properties: omitExternalRequestsFromAppShell: Boolean description: If true, omits requests to external domains from the default app shell caching strategies. If false (default), requests to external domains will be cached in the app shell. Note that this setting does not affect the recording mode. ```