### Quick Start Project Setup Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/getting-started.md Use these commands to quickly create a new React app, navigate into its directory, and start the development server. ```sh npx create-react-app my-app cd my-app npm start ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/react/create-react-app/blob/main/docusaurus/website/README.md Installs all necessary packages for the project. ```bash npm install ``` -------------------------------- ### Install and Run Serve CLI Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/deployment.md Install the 'serve' package globally and use it to serve the production build directory. ```sh npm install -g serve serve -s build ``` -------------------------------- ### Install Dependencies Source: https://github.com/react/create-react-app/blob/main/CONTRIBUTING.md Install project dependencies in the docusaurus/website directory before building. ```bash npm ci ``` -------------------------------- ### Start Styleguidist Server Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/developing-components-in-isolation.md Run this command to start the Styleguidist development server after adding the necessary scripts. ```sh npm run styleguide ``` -------------------------------- ### Configure Web App Manifest Start URL Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/deployment.md Modify the start_url in the public/manifest.json file to '.' to ensure client-side routers are served from the root directory when the app is installed to the homescreen. ```json "start_url": ".", ``` -------------------------------- ### Install graphql and graphql.macro with npm Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/loading-graphql-files.md Install the necessary packages using npm to enable loading GraphQL files. ```sh npm install --save graphql graphql.macro ``` -------------------------------- ### Original CSS Example Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/post-processing-css.md This is an example of CSS before post-processing. ```css .App { display: flex; flex-direction: row; align-items: center; } ``` -------------------------------- ### Start Local Development Server Source: https://github.com/react/create-react-app/blob/main/docusaurus/website/README.md Starts a local development server for live previewing changes. Changes are reflected without server restart. ```bash npm start ``` -------------------------------- ### Install babel-preset-react-app Source: https://github.com/react/create-react-app/blob/main/packages/babel-preset-react-app/README.md Install the babel-preset-react-app package as a development dependency using npm. ```sh npm install babel-preset-react-app --save-dev ``` -------------------------------- ### Install Flow Bin Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-flow.md Install the Flow binary as a development dependency. Use either npm or yarn. ```bash npm install --save flow-bin ``` ```bash yarn add flow-bin ``` -------------------------------- ### Create New React App with TypeScript Template Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-typescript.md Use this command to start a new Create React App project with TypeScript pre-configured. Ensure you have npx or yarn installed. ```sh npx create-react-app my-app --template typescript ``` ```sh yarn create react-app my-app --template typescript ``` -------------------------------- ### Install react-app-polyfill with Yarn Source: https://github.com/react/create-react-app/blob/main/packages/react-app-polyfill/README.md Install the react-app-polyfill package using Yarn. This is an alternative to npm for package installation. ```sh yarn add react-app-polyfill ``` -------------------------------- ### Example .graphql file content Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/loading-graphql-files.md This is an example of what a .graphql file might contain, defining a simple GraphQL query. ```graphql query { hello { world } } ``` -------------------------------- ### Install graphql and graphql.macro with yarn Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/loading-graphql-files.md Install the necessary packages using yarn to enable loading GraphQL files. ```sh yarn add graphql graphql.macro ``` -------------------------------- ### Install http-proxy-middleware Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/proxying-api-requests-in-development.md Install the `http-proxy-middleware` package using npm or Yarn to enable manual proxy configuration. ```sh $ npm install http-proxy-middleware --save $ # or $ yarn add http-proxy-middleware ``` -------------------------------- ### Install react-app-polyfill with npm Source: https://github.com/react/create-react-app/blob/main/packages/react-app-polyfill/README.md Install the react-app-polyfill package using npm. This is a prerequisite for using the polyfills. ```sh npm install react-app-polyfill ``` -------------------------------- ### Clone and Install Create React App Locally Source: https://github.com/react/create-react-app/blob/main/CONTRIBUTING.md Clone the Create React App repository and install its dependencies to set up a local development environment. ```sh git clone https://github.com/facebook/create-react-app npm install ``` -------------------------------- ### Install Confusing Browser Globals Source: https://github.com/react/create-react-app/blob/main/packages/confusing-browser-globals/README.md Installs the `confusing-browser-globals` package as a project dependency. ```sh npm install --save confusing-browser-globals ``` -------------------------------- ### Manual Deployment to Netlify Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/deployment.md Install the Netlify CLI and initiate a manual deployment. Choose 'build' as the deployment path. ```sh npm install netlify-cli -g netlify deploy ``` -------------------------------- ### Install Source map explorer with yarn Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/analyzing-the-bundle-size.md Install the source-map-explorer package using yarn. This is an alternative to npm for package installation. ```sh yarn add source-map-explorer ``` -------------------------------- ### Install React Styleguidist Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/developing-components-in-isolation.md Install React Styleguidist as a project dependency using npm or yarn. ```sh npm install --save react-styleguidist ``` ```sh yarn add react-styleguidist ``` -------------------------------- ### Setting Up Test Environment with `src/setupTests.js` Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/running-tests.md Create `src/setupTests.js` to automatically execute setup code before tests run. This is useful for mocking browser APIs like localStorage. ```javascript const localStorageMock = { getItem: jest.fn(), setItem: jest.fn(), removeItem: jest.fn(), clear: jest.fn(), }; global.localStorage = localStorageMock; ``` -------------------------------- ### Install Dependency with npm Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/installing-a-dependency.md Use this command to install any new library, such as React Router, using npm. ```bash npm install --save react-router-dom ``` -------------------------------- ### Install Babel Plugin Relay with Yarn Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-relay.md Use this command to install the babel-plugin-relay package using yarn. ```sh yarn add babel-plugin-relay ``` -------------------------------- ### Install Babel Plugin Relay with npm Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-relay.md Use this command to install the babel-plugin-relay package using npm. ```sh npm install --save babel-plugin-relay ``` -------------------------------- ### Start Development Server Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/getting-started.md Runs the app in development mode, providing hot-reloading and displaying build errors in the console. Access the app at http://localhost:3000. ```bash npm start ``` ```bash yarn start ``` -------------------------------- ### Install Source map explorer with npm Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/analyzing-the-bundle-size.md Install the source-map-explorer package using npm. This is the first step to enable bundle size analysis. ```sh npm install --save source-map-explorer ``` -------------------------------- ### Install Sass Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-a-sass-stylesheet.md Install the `sass` package to enable Sass compilation in your project. This is required for using `.scss` or `.sass` files. ```sh $ npm install sass # or $ yarn add sass ``` -------------------------------- ### Install gh-pages and Add Deploy Scripts Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/deployment.md Install the gh-pages package and add predeploy and deploy scripts to your package.json. The predeploy script ensures the app is built before deployment. ```diff "scripts": { + "predeploy": "npm run build", + "deploy": "gh-pages -d build", "start": "react-scripts start", "build": "react-scripts build", ``` -------------------------------- ### Install env-cmd for Custom Environments Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/deployment.md Install `env-cmd` to manage custom build environments. This is necessary before configuring custom scripts in `package.json`. ```sh $ npm install env-cmd --save $ # or $ yarn add env-cmd ``` -------------------------------- ### Install TypeScript and Types for Existing Project Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-typescript.md Install TypeScript and necessary type definitions for Node, React, and Jest to an existing Create React App project. This is required before renaming files to .ts or .tsx. ```sh npm install --save typescript @types/node @types/react @types/react-dom @types/jest ``` ```sh yarn add typescript @types/node @types/react @types/react-dom @types/jest ``` -------------------------------- ### Install Prettier and Git Hooks Dependencies (npm) Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/setting-up-your-editor.md Install husky, lint-staged, and prettier using npm. These tools enable pre-commit hooks for automatic code formatting. ```sh npm install --save husky lint-staged prettier ``` -------------------------------- ### Deploy Website to GitHub Pages Source: https://github.com/react/create-react-app/blob/main/docusaurus/website/README.md Builds the website and pushes it to the 'gh-pages' branch for GitHub Pages hosting. Requires GitHub username and SSH setup. ```bash GIT_USER= USE_SSH=1 npm run deploy ``` -------------------------------- ### Install React Router with npm Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-a-router.md Use this command to add the react-router-dom package to your project using npm. ```sh npm install react-router-dom ``` -------------------------------- ### Install React Testing Library and Jest DOM (npm) Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/running-tests.md Installs the necessary packages for using React Testing Library and jest-dom with npm. These libraries facilitate testing React components in a user-centric way. ```sh npm install --save @testing-library/react @testing-library/dom @testing-library/jest-dom ``` -------------------------------- ### Create PWA Project with CRA Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/making-a-progressive-web-app.md Use this command to start a new React project with PWA template support. ```bash npx create-react-app my-app --template cra-template-pwa ``` -------------------------------- ### Install Prettier and Git Hooks Dependencies (yarn) Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/setting-up-your-editor.md Install husky, lint-staged, and prettier using yarn. These tools enable pre-commit hooks for automatic code formatting. ```sh yarn add husky lint-staged prettier ``` -------------------------------- ### Install React Router with yarn Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-a-router.md Use this command to add the react-router-dom package to your project using yarn. ```sh yarn add react-router-dom ``` -------------------------------- ### Install React Testing Library and Jest DOM (yarn) Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/running-tests.md Installs the necessary packages for using React Testing Library and jest-dom with yarn. These libraries facilitate testing React components in a user-centric way. ```sh yarn add @testing-library/react @testing-library/dom @testing-library/jest-dom ``` -------------------------------- ### Install Bootstrap CSS Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-bootstrap.md Install the Bootstrap package using npm or yarn. This command is used to add the core Bootstrap CSS files to your project. ```sh npm install bootstrap ``` ```sh yarn add bootstrap ``` -------------------------------- ### Configure HTTPS in npm start script Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/using-https-in-development.md Include the HTTPS=true environment variable directly in the npm start script within your package.json file to automatically enable HTTPS. ```json { "start": "HTTPS=true react-scripts start" } ``` -------------------------------- ### Manually Format Entire Project Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/setting-up-your-editor.md Run Prettier manually to format all specified files in the 'src' directory. This is useful for initial setup or a full project reformat. ```sh ./node_modules/.bin/prettier --write "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}" ``` -------------------------------- ### Install gh-pages with Yarn Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/deployment.md Alternatively, use Yarn to add the gh-pages package to your project dependencies. ```sh yarn add gh-pages ``` -------------------------------- ### Importing Third-Party Assertion Libraries Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/running-tests.md Import Chai and Sinon to use them in your tests. Ensure these libraries are installed in your project. ```javascript import sinon from 'sinon'; import { expect } from 'chai'; ``` -------------------------------- ### Importing a Module with Absolute Path Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/importing-a-component.md Demonstrates how to import a module using an absolute path after configuring jsconfig.json or tsconfig.json. The path starts from the configured baseUrl. ```javascript import Button from 'components/Button'; ``` -------------------------------- ### Basic setupProxy.js Configuration Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/proxying-api-requests-in-development.md Create a `src/setupProxy.js` file and import `createProxyMiddleware` to begin configuring your proxy. ```javascript const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function (app) { // ... }; ``` -------------------------------- ### Display Serve CLI Help Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/deployment.md View all available options and commands for the 'serve' package. ```sh serve -h ``` -------------------------------- ### Create React App with npx Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/getting-started.md This command uses npx to create a new React application named 'my-app'. Ensure you have Node.js version 14 or higher installed. ```sh npx create-react-app@latest my-app ``` -------------------------------- ### Print Hosting Instructions Source: https://github.com/react/create-react-app/blob/main/packages/react-dev-utils/README.md Prints hosting instructions to the console after a project build. Requires parsed package.json, public URL, public path, build folder name, and yarn usage flag. ```javascript const appPackage = require(paths.appPackageJson); const publicUrl = paths.publicUrlOrPath; const publicPath = config.output.publicPath; printHostingInstructions(appPackage, publicUrl, publicPath, 'build', true); ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/getting-started.md After creating the app, change into the new project directory to access its files and run scripts. ```bash cd my-app ``` -------------------------------- ### Initialize Storybook for React Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/developing-components-in-isolation.md Run this command in your app's directory to set up Storybook for React development. ```sh npx sb init ``` -------------------------------- ### printHostingInstructions Source: https://github.com/react/create-react-app/blob/main/packages/react-dev-utils/README.md Prints hosting instructions to the console after a project has been built. It takes details about the application package, public URL, public path, build folder, and whether Yarn is being used. ```APIDOC ## printHostingInstructions(appPackage: Object, publicUrl: string, publicPath: string, buildFolder: string, useYarn: boolean): void ### Description Prints hosting instructions after the project is built. This function is useful for providing guidance to users on how to host their built React application. ### Parameters - **appPackage** (Object) - Required - The parsed `package.json` object. - **publicUrl** (string) - Required - The URL where the app will be hosted. - **publicPath** (string) - Required - The `output.publicPath` from the webpack configuration. - **buildFolder** (string) - Required - The name of the build folder. - **useYarn** (boolean) - Required - Indicates whether to use Yarn for instructions. ``` -------------------------------- ### Build for Production Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/getting-started.md Creates an optimized production build of the app in the `build` folder. The output is minified and includes hashed filenames for efficient deployment. ```bash npm run build ``` ```bash yarn build ``` -------------------------------- ### Firebase Initialization Prompts Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/deployment.md This output shows the interactive prompts and selections during the `firebase init` command for setting up Firebase Hosting. ```sh === Project Setup First, let's associate this project directory with a Firebase project. You can create multiple project aliases by running firebase use --add, but for now we'll set up a default project. ? What Firebase project do you want to associate as default? Example app (example-app-fd690) === Database Setup Firebase Realtime Database Rules allow you to define how your data should be structured and when your data can be read from and written to. ? What file should be used for Database Rules? database.rules.json ✔ Database Rules for example-app-fd690 have been downloaded to database.rules.json. Future modifications to database.rules.json will update Database Rules when you run firebase deploy. === Hosting Setup Your public directory is the folder (relative to your project directory) that will contain Hosting assets to uploaded with firebase deploy. If you have a build process for your assets, use your build's output directory. ? What do you want to use as your public directory? build ? Configure as a single-page app (rewrite all urls to /index.html)? Yes ✔ Wrote build/index.html i Writing configuration info to firebase.json... i Writing project information to .firebaserc... ✔ Firebase initialization complete! ``` -------------------------------- ### Deploy Documentation Source: https://github.com/react/create-react-app/blob/main/CONTRIBUTING.md Deploy the documentation using npm, specifying the Git user, current branch, and SSH usage. ```bash GIT_USER= CURRENT_BRANCH=main USE_SSH=true npm run deploy ``` -------------------------------- ### Install Sass Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-bootstrap.md Install the Sass compiler using npm or yarn. This is required if you plan to use custom Sass themes with Bootstrap. ```sh npm install sass ``` ```sh yarn add sass ``` -------------------------------- ### Example CORS Error Message Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/proxying-api-requests-in-development.md This is an example of a CORS error message you might encounter if API requests are not proxied correctly during development. ```text Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. ``` -------------------------------- ### Create React App with npm Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/getting-started.md Use this command with npm version 6 or higher to initialize a new React application. This is an alternative to using npx. ```sh npm init react-app my-app ``` -------------------------------- ### Create a New React App Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/getting-started.md Use this command to generate a new React project directory with a standard file structure and dependencies. ```bash npx create-react-app my-app ``` ```bash npm init react-app my-app ``` ```bash yarn create react-app my-app ``` -------------------------------- ### Serve with Custom Port using Serve CLI Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/deployment.md Serve the production build directory on a custom port using the 'serve' package. ```sh serve -s build -l 4000 ``` -------------------------------- ### Run Deployment Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/deployment.md Execute the npm run deploy command to build your React application and publish it to GitHub Pages. ```sh npm run deploy ``` -------------------------------- ### CSS Modules Stylesheet Example Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-a-css-modules-stylesheet.md Define locally scoped CSS class names using the `.module.css` file extension. This example shows a simple `.error` class. ```css .error { background-color: red; } ``` -------------------------------- ### Install ESLint and react-app config Source: https://github.com/react/create-react-app/blob/main/packages/eslint-config-react-app/README.md Install the necessary packages for using eslint-config-react-app outside of a Create React App project. Ensure you are using ESLint version 8.0.0 or higher. ```sh npm install --save-dev eslint-config-react-app eslint@^8.0.0 ``` -------------------------------- ### Initialize Flow Configuration Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-flow.md Initialize Flow in your project to create a .flowconfig file. Use either npm or yarn. ```bash npm run flow init ``` ```bash yarn flow init ``` -------------------------------- ### Run Build with CI=true on Windows (cmd.exe) Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/running-tests.md Sets the CI environment variable to true and runs npm run build using the Windows command prompt. ```cmd set CI=true&&npm run build ``` -------------------------------- ### Create PWA Project with CRA (TypeScript) Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/making-a-progressive-web-app.md Use this command to start a new TypeScript React project with PWA template support. ```bash npx create-react-app my-app --template cra-template-pwa-typescript ``` -------------------------------- ### Netlify Client-Side Routing Support Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/deployment.md Create a _redirects file in the public folder to enable pushState support for client-side routing. ```text /* /index.html 200 ``` -------------------------------- ### Regular Stylesheet Example Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-a-css-modules-stylesheet.md Define a regular CSS class. This class name might clash with class names in other stylesheets if not managed carefully. ```css .error { color: red; } ``` -------------------------------- ### Example of Accidental Global Usage Source: https://github.com/react/create-react-app/blob/main/packages/confusing-browser-globals/README.md Demonstrates how `event` can be mistakenly used as a global variable in a React component's `handleClick` method, leading to an error. ```javascript handleClick() { // missing `event` argument this.setState({ text: event.target.value // uses the `event` global: oops! }); } ``` -------------------------------- ### Basic Jest Test Example Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/running-tests.md A simple test case using `it()` and `expect()` to assert the output of a function. Ensure the `sum` function is imported from its respective file. ```javascript import sum from './sum'; it('sums numbers', () => { expect(sum(1, 2)).toEqual(3); expect(sum(2, 2)).toEqual(4); }); ``` -------------------------------- ### Basic Component Smoke Test Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/running-tests.md This test verifies that a React component renders without throwing errors. It's a good starting point for component testing. ```javascript import React from 'react'; import ReactDOMClient from 'react-dom/client'; import App from './App'; it('renders without crashing', () => { const div = document.createElement('div'); ReactDOMClient.createRoot(div).render(); }); ``` -------------------------------- ### Test End-to-End Flow with Global CLI Source: https://github.com/react/create-react-app/blob/main/CONTRIBUTING.md Use npx to create a new React app and navigate into its directory to test the end-to-end flow. ```sh npx create-react-app my-app cd my-app ``` -------------------------------- ### Build and Analyze Bundle Size Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/analyzing-the-bundle-size.md Run the production build and then execute the analyze script to view the bundle size breakdown. This process helps identify code bloat. ```sh npm run build npm run analyze ``` -------------------------------- ### Migrate from Node Sass to Dart Sass Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-a-sass-stylesheet.md If you are currently using Node Sass, migrate to Dart Sass for continued support. This involves uninstalling `node-sass` and installing `sass`. ```sh $ npm uninstall node-sass $ npm install sass # or $ yarn remove node-sass $ yarn add sass ``` -------------------------------- ### Integrate Create React App with Express Server Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/deployment.md Programmatically serve static assets from the 'build' directory and handle root requests by sending the 'index.html' file using Express. ```javascript const express = require('express'); const path = require('path'); const app = express(); app.use(express.static(path.join(__dirname, 'build'))); app.get('/', function (req, res) { res.sendFile(path.join(__dirname, 'build', 'index.html')); }); app.listen(9000); ``` -------------------------------- ### Custom Service Worker with Ignored Manifest Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/making-a-progressive-web-app.md When creating a custom service worker, ensure `self.__WB_MANIFEST` is present. This example shows how to assign it to an ignored variable if you don't need precaching. ```javascript // eslint-disable-next-line no-restricted-globals const ignored = self.__WB_MANIFEST; // Your custom service worker code goes here. ``` -------------------------------- ### Build for Production Source: https://github.com/react/create-react-app/blob/main/README.md Command to create a minified bundle of your React application for production deployment. ```sh npm run build ``` -------------------------------- ### Run E2E Tests with Docker Source: https://github.com/react/create-react-app/blob/main/CONTRIBUTING.md Execute unit and end-to-end tests for Create React App using the provided npm script. This command is the recommended way to run tests. ```sh npm run e2e:docker ``` -------------------------------- ### Configuring Absolute Imports with jsconfig.json Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/importing-a-component.md Sets up the project to allow importing modules using absolute paths starting from the 'src' directory. This requires a jsconfig.json file at the project root. ```json { "compilerOptions": { "baseUrl": "src" }, "include": ["src"] } ``` -------------------------------- ### Add CNAME File for Custom Domain Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/deployment.md To use a custom domain, create a CNAME file in the public/ folder of your project with your domain name. ```text mywebsite.com ``` -------------------------------- ### Referencing Environment Variables in HTML Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-custom-environment-variables.md Access environment variables starting with REACT_APP_ directly within your public/index.html file. Ensure variables are prefixed correctly and understand they are injected at build time. ```html %REACT_APP_WEBSITE_NAME% ``` -------------------------------- ### Setup Jest DOM Custom Assertions Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/running-tests.md Configures jest-dom's custom assertions in your test environment by importing the library into your setupTests.js file. This enhances testing capabilities for React components. ```javascript // react-testing-library renders your components to document.body, // this adds jest-dom's custom assertions import '@testing-library/jest-dom'; ``` -------------------------------- ### Root Links with React Router Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/deployment.md When using `react-router@^4`, you can root `` elements using the `basename` prop on a `` component. This example shows how a link is rendered with a prepended base path. ```jsx // renders ``` -------------------------------- ### Add Styleguidist Scripts to package.json Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/developing-components-in-isolation.md Add these scripts to your package.json file to enable running and building the Styleguidist server. ```diff "scripts": { + "styleguide": "styleguidist server", + "styleguide:build": "styleguidist build", "start": "react-scripts start", ``` -------------------------------- ### Register Proxy with http-proxy-middleware Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/proxying-api-requests-in-development.md Register a proxy for the `/api` path using `http-proxy-middleware` in `src/setupProxy.js`, targeting `http://localhost:5000`. ```javascript const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function (app) { app.use( '/api', createProxyMiddleware({ target: 'http://localhost:5000', changeOrigin: true, }) ); }; ``` -------------------------------- ### Defining Permanent Environment Variables in .env Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/adding-custom-environment-variables.md Create a .env file in your project root to define permanent environment variables. Variables must start with REACT_APP_ to be recognized. Remember to restart the development server after changes. ```env REACT_APP_NOT_SECRET_CODE=abcdef ``` -------------------------------- ### Import and use loader for .graphql files Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/loading-graphql-files.md Import the `loader` from `graphql.macro` to load GraphQL query definitions from .graphql files. ```javascript import { loader } from 'graphql.macro'; const query = loader('./foo.graphql'); ``` -------------------------------- ### Jest Configuration in package.json Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/running-tests.md You can override Create React App's default Jest configuration by adding supported keys to a Jest config object in your package.json. This example shows how to configure coverage collection, thresholds, reporters, and snapshot serializers. ```json { "name": "your-package", "jest": { "collectCoverageFrom": [ "src/**/*.{js,jsx,ts,tsx}", "!/node_modules/", "!/path/to/dir/" ], "coverageThreshold": { "global": { "branches": 90, "functions": 90, "lines": 90, "statements": 90 } }, "coverageReporters": ["text"], "snapshotSerializers": ["my-serializer-module"] } } ``` -------------------------------- ### Measure and Print File Sizes Before and After Build Source: https://github.com/react/create-react-app/blob/main/packages/react-dev-utils/README.md Capture JS and CSS asset sizes before a build and print them with comparison after the build. Optionally specify max bundle and chunk sizes for warnings. ```javascript var { measureFileSizesBeforeBuild, printFileSizesAfterBuild, } = require('react-dev-utils/FileSizeReporter'); measureFileSizesBeforeBuild(buildFolder).then(previousFileSizes => { return cleanAndRebuild().then(webpackStats => { printFileSizesAfterBuild(webpackStats, previousFileSizes, buildFolder); }); }); ``` -------------------------------- ### Create React App with Yarn Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/getting-started.md If you prefer Yarn, use this command with Yarn version 0.25 or higher to create a new React application. ```sh yarn create react-app my-app ``` -------------------------------- ### Run Tests with CI=true on Windows (cmd.exe) Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/running-tests.md Sets the CI environment variable to true and runs npm test using the Windows command prompt. ```cmd set CI=true&&npm test ``` -------------------------------- ### Dynamic Import with Promise Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/code-splitting.md Demonstrates loading 'moduleA' dynamically using `import()` and handling the resolved module with `.then()`. This snippet is useful for loading components or features only when a user action, like a button click, occurs. ```javascript import React, { Component } from 'react'; class App extends Component { handleClick = () => { import('./moduleA') .then(({ moduleA }) => { // Use moduleA }) .catch(err => { // Handle failure }); }; render() { return (
); } } export default App; ``` -------------------------------- ### Create App with a Custom Template Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/custom-templates.md Use this command to create a new React app using a specified custom template. Replace `[template-name]` with the actual name of your template. ```sh npx create-react-app my-app --template [template-name] ``` -------------------------------- ### Enable Production Build Profiling Source: https://github.com/react/create-react-app/blob/main/docusaurus/docs/production-build.md Use the `--profile` flag with your build command to enable profiling in production builds. This allows for performance analysis using React DevTools. ```bash npm run build -- --profile ``` ```bash yarn build --profile ```