Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

How to Use React-Scripts to Build Amazing User Interfaces

React Scripts

Setting up a React app from scratch can be complex due to the need for building tools like Webpack and Babel. Fortunately, Create React App (CRA) makes it easy to start building React apps without this configuration headache.

At the core of CRA is the react-scripts package which abstracts away the complex configuration of underlying tools. In this comprehensive guide, we will explain react-scripts and explore how CRA utilizes Babel, ESLint, Jest, PostCSS, and Webpack under the hood. We compare building UIs using React versus traditional jQuery methods and cover other key topics related to react-scripts and CRA. Whether you are new to React or an experienced user looking to better understand CRA’s inner workings, this article has you covered.

Before we delve further, let me quickly introduce you to Purecode AI

Purecode AI is an innovative AI assistant that can generate thousands of custom HTML, CSS, and JavaScript components for web development. It provides an extensive library of responsive, pre-made components that come with default styling out of the box. You can easily customize these components by tweaking colors, spacing, paddings, and more to match their brand design needs.

Purecode landing

What Is React Script?

React Script is a package that includes scripts and configurations used by Create React App (CRA). It abstracts the build configuration, allowing you to focus on the code.

When you run npx create-react-app my-app, it sets up a new React application with React Script already configured. This means you don’t have to worry about setting up Babel, Webpack, and other build tools.

Here’s a simple illustration of how you might use React Script in your project:

# Step 1: Create a new React application using Create React App
npx create-react-app my-app

# Step 2: Move into the new project directory
cd my-app

# Step 3: Start the development server
npm start

When you run npm start, React Script takes over, starts a development server, and opens your application in a web browser. As you save changes to your code, React Script automatically reloads your application with the latest changes.

React Script also provides other scripts like npm run build for building a production-ready version of your application, and npm test for running tests.

While React Script abstracts away the build configuration, it also provides an “eject” feature for more advanced use cases. Running npm run eject will remove the single build dependency from your project and move all configuration files and transitive dependencies (Webpack, Babel, ESLint, etc) right into your project, allowing you full control over the build setup. However, this operation is irreversible.

# Eject from Create React App
npm run eject

CRA Dependencies

Facebook built a tool, Create React App (CRA), to help you create React applications with no build configuration. It uses the react-scripts package which manages all the dependencies and scripts for your project. When you create a new project using CRA, it sets up a “black box” of dependencies which abstract away in the react-scripts package.

Here’s a brief overview of some key dependencies that come with a new CRA project:

react, react-dom, and react-scripts

These are the core dependencies of a CRA project. react and react-dom are the packages that allow you to use React in your application. react-scripts is a set of scripts from the CRA team that includes the scripts to start, build, and test your application.

"dependencies": {
  "react": "^17.0.2",
  "react-dom": "^17.0.2",
  "react-scripts": "4.0.3"
}

Babel, ESLint, Webpack, and Jest

These are not listed in your package.json file because they’re abstracted away in react-scripts. However, they’re crucial to the build process:

  • Babel: This is a JavaScript compiler that converts ES6 and JSX syntax into plain JavaScript that is understandable to the browser.

  • ESLint: This is a pluggable linting utility for JavaScript that is used to find and fix problems in your JavaScript code.

  • Webpack: This is a static module bundler for modern JavaScript applications. It creates a dependency graph of your application and uses this to generate a bundle of static assets.

  • Jest: Jest is a JavaScript testing framework maintained by Facebook. It’s used for writing and running tests in your CRA application. Like Babel, ESLint, and Webpack, Jest is also abstracted away in react-scripts.

Other Dependencies

Many other dependencies are installed with a new CRA project, including loaders for Webpack, polyfills for older browsers, and more. These are all abstracted away in react-scripts to provide a seamless developer experience.

Understanding Babel in CRA

Babel

Babel is a crucial part of Create React App (CRA). It’s a JavaScript compiler that transforms modern JavaScript (ES6+) and JSX into backward-compatible JavaScript code that can run in older browsers.

Role of Babel in CRA

In the context of a React application, Babel has two main roles:

  1. Transpiling ES6+ to ES5: JavaScript is continually evolving, with new features being added every year. However, not all browsers can understand these new features. Babel allows developers to write modern JavaScript and then, it transpiles it into ES5, which is widely supported by browsers.

  2. Transforming JSX: React introduces JSX, a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. Babel compiles this JSX into React.createElement() calls.

Here’s an example of how Babel transforms JSX:

// JSX code
const element = <h1>Hello, world!</h1>;

// After Babel transpiles the JSX
const element = React.createElement("h1", null, "Hello, world!");

Babel Configuration in CRA

In a CRA project, Babel’s configuration is abstracted away in react-scripts, so you don’t have to worry about setting it up yourself. However, if you’re curious, you can find the configuration in node_modules/react-scripts/config/webpack.config.js.

The Babel configuration in CRA includes presets such as @babel/preset-env for transpiling modern JavaScript and @babel/preset-react for transforming JSX.

Customizing Babel Configuration

While CRA doesn’t allow you to override the Babel configuration directly, you can use the eject command to expose all the configuration files. However, this is a one-way operation and is generally not recommended unless you have a specific need for customization that CRA doesn’t support.

ESLint in Create React App

ESLint

ESLint is a static code analysis tool for identifying problematic patterns found in JavaScript code. It’s a pluggable and configurable linter tool for identifying and reporting patterns in JavaScript.

Role of ESLint in CRA

In the context of Create React App (CRA), ESLint is set up out of the box with a configuration that favors developer experience and is optimized for building React applications. It helps to maintain code quality and adhere to best practices.

Here’s an example of how ESLint might flag an issue in your code:

// JavaScript code with a problem
function add(a, b) {
  return a + b
}

// ESLint will flag the missing semicolon
// Expected an assignment or function call and instead saw an expression. (no-unused-expressions)

ESLint Configuration in CRA

The configuration for ESLint in CRA is abstracted away in react-scripts. However, if you’re curious, you can find the configuration in node_modules/react-scripts/config/webpack.config.js.

The ESLint configuration in CRA includes rules that are considered problematic by the JavaScript community. For example, it flags variables that are declared but not used, missing semicolons, unreachable code, and more.

Customizing ESLint Configuration

While CRA doesn’t allow you to override the ESLint configuration directly, you can add a .eslintrc file at the root of your project to customize ESLint rules. Here’s an example:

{
  "extends": "react-app",
  "rules": {
    "semi": ["error", "always"],
    "quotes": ["error", "double"]
  }
}

In this configuration, we’re extending the base ESLint configuration provided by CRA (react-app) and adding two rules: one to enforce semicolons and another to enforce the use of double quotes.

Jest Testing in CRA

Jest

As noted earlier, Jest is a delightful JavaScript testing framework maintained by Facebook, and it’s set up for you when you create a new app using Create React App (CRA). It provides a simple way to test React components and ensures your application works as expected.

Why Jest?

Many choose Jest for a few reasons:

  • Zero configuration: Jest works out of the box with minimal setup.

  • Snapshot testing: This feature allows you to capture the state of your UI and then compare it to a reference snapshot stored alongside your test.

  • Parallelized testing: Jest runs tests in parallel processes, making it significantly faster.

Writing Your First Test

Let’s write a simple test for a React component. Consider a Button component:

import React from 'react';

const Button = ({ onClick, children }) => (
  <button onClick={onClick}>{children}</button>
);

export default Button;

You can write a test for this Button component like so:

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Button from './Button';

test('renders the correct content', () => {
  const onClick = jest.fn();
  const { getByText } = render(<Button onClick={onClick}>Click Me!</Button>);

  // Assert the button content
  expect(getByText('Click Me!')).not.toBeNull();

  // Simulate a click event
  fireEvent.click(getByText('Click Me!'));

  // Assert the onClick handler is called
  expect(onClick).toHaveBeenCalled();
});

In the test above, we’re using @testing-library/react to render our component and then assert that the button’s content is correct. We also simulate a click event and assert to call the onClick handler.

Running Tests

To run your tests, you can use the npm test or yarn test command in your terminal. This will start Jest in watch mode. Any time you save a file, it will re-run the tests.

PostCSS Transformation in CRA

PostCSS

PostCSS is a great tool that transforms styles with JavaScript plugins. It’s used in Create React App (CRA) to provide a seamless styling experience.

What is PostCSS?

PostCSS is a post-processor for CSS. It allows you to transform your CSS with JavaScript plugins. These plugins can support variables and [mixins(https://javascript.info/mixins)], transpile future CSS syntax, inline images, and more.

How does CRA use PostCSS?

CRA uses PostCSS out of the box. When you run npm start or npm run build, CRA uses PostCSS to apply various transformations to your CSS.

PostCSS Features in CRA

Here are some of the features PostCSS provides in CRA:

  • Autoprefixer: This plugin automatically adds vendor prefixes to your CSS. You don’t need to worry about adding webkit- or moz- prefixes; Autoprefixer handles it for you.

  • CSS Modules: This feature scopes CSS by automatically creating unique class names. It helps avoid naming collisions and keeps styles encapsulated to components.

  • CSS Next: This plugin allows you to use future CSS features today. It transforms new CSS syntax into current syntax that browsers understand.

Using PostCSS in CRA

You don’t need to do anything special to use PostCSS in CRA. It’s configured out of the box. Here’s an example of how you might write CSS using some PostCSS features:

/* Using CSS Variables */
:root {
  --main-color: #123456;
}

.myComponent {
  /* Using CSS Variables */
  background-color: var(--main-color);

  /* Using future CSS syntax */
  color: color-mod(var(--main-color) lightness(50%));
}

In the example above, we’re using CSS variables and a future CSS syntax feature called color-mod.

Webpack in Create React App

Webpack

Webpack is a powerful module bundler in Create React App (CRA) that bundles JavaScript files and assets for usage in the browser.

What is Webpack?

Webpack is a tool that lets you compile JavaScript modules, also known as bundling. It takes modules with dependencies and generates static assets representing those modules. It’s highly configurable but also works well out of the box for beginners.

How does CRA use Webpack?

CRA uses Webpack under the hood to bundle your app. When you run npm start or npm run build, CRA uses Webpack to bundle your JavaScript, CSS, and other assets into a package that a browser can serve.

Webpack Features in CRA

Here are some of the features Webpack provides in CRA:

  • Code Splitting: This feature allows you to split your code into various bundles which can then be loaded on demand or in parallel. It can be used to achieve smaller bundles and control resource load prioritization which, if used correctly, can have a major impact on load time.

  • Loaders: Webpack enables the use of loaders to preprocess files. This allows you to bundle any static resource way beyond JavaScript. You can easily write your loaders using Node.js.

  • Plugins: Webpack has a rich plugin interface. Most of the features within webpack itself use this plugin interface. This makes Webpack very flexible.

Using Webpack in CRA

You don’t need to do anything special to use Webpack in CRA. It’s configured out of the box. However, if you want to customize the Webpack configuration, you can “eject” from CRA by running npm run eject. This will expose all the configuration files and scripts, including the Webpack configuration.

Here’s an example of how you might import a module using ES6 syntax, which Webpack will then bundle:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

In the example above, we’re importing the React, ReactDOM, and App modules. Webpack will bundle these modules together into a single JavaScript file that can be served to the browser.

Exploring react-scripts

react-scripts is a set of scripts from the Create React App (CRA) project. It abstracts away the configuration for tools like Babel and Webpack and provides a smooth developer experience.

What is react-scripts?

react-scripts is a development dependency in the generated projects of Create React App (CRA). It includes scripts and configurations used by CRA. You’ll interact with react-scripts when using commands like npm start and npm run build.

Key Scripts Provided by react-scripts

react-scripts provides the following scripts:

  • start: Runs the app in development mode. It starts the development server and enables hot module reloading.

  • build: Build the app for production to the build folder. It correctly bundles React in production mode and optimizes the build for the best performance.

  • test: Runs the test watcher in an interactive mode. It runs all tests related to files changed since the last commit.

  • eject: Removes the single build dependency from your project and copies all the configuration files and transitive dependencies into your project, allowing you to customize the configuration as you see fit.

Using react-scripts in Your Project

When you bootstrap a new project using CRA, your package.json scripts section will look something like this:

"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
}

You can run these scripts using npm run <script> or yarn <script>. For example, to start your development server, you would run npm run start.

Customizing Configuration

By default, the configuration files are hidden and the project works out of the box with no configuration options. However, if you want to customize the configuration, you can run npm run eject. This command will move all the configuration files and the transitive dependencies into your project, giving you full control over the configuration.

Using react-scripts start

The react-scripts start command is used to start your application in development mode. It’s part of the react-scripts package, which is included in all projects created with the Create React App (CRA).

What does react-script-start do?

When you run react-scripts start, several things happen:

  1. Development Server: A local development server starts. This server serves your app at localhost:3000 by default.

  2. Hot Module Replacement: The server uses “Hot Module Replacement” (HMR). This means that when you make changes to your code, those changes are automatically updated in the browser without a full page refresh.

  3. Error Overlay: If there are any errors in your code, you’ll see an error overlay in your app in the browser. This helps you quickly identify and fix issues.

  4. Linting Warnings: If there are any linting warnings in your code (for example, if you’ve violated the rules set up by ESLint), those warnings will be displayed in the console.

How to use react-scripts start

To start your app in development mode, you need to run the start script in your package.json. You can do this by running the following command in your terminal:

npm start

Or, if you’re using Yarn:

yarn start

This will start your app, and you can view it by opening http://localhost:3000 in your browser.

Example

Let’s say you have a simple React app with an App component:

import React from 'react';

function App() {
  return <h1>Hello, world!</h1>;
}

export default App;

You can start this app by running npm start or yarn start. Then, if you open http://localhost:3000 in your browser, you’ll see “Hello, world!” displayed on the page.

Utilizing react-scripts build

The react-scripts build command is used to create a production-ready build of your application. It’s part of the react-scripts package, which is included in all projects created with the Create React App (CRA).

What does react-scripts build do?

When you run react-scripts build, several things happen:

  1. Code Optimization: Your React code minifies and optimizes for performance. This includes removing comments and whitespace, transforming the code for better performance, and more.

  2. Asset Optimization: All your assets (like images and fonts) are optimized. They’re renamed with hashes for cache busting and smaller images are inlined to save HTTP requests.

  3. CSS Extraction: Your CSS is extracted from your JavaScript bundles into separate CSS files. This allows the browser to cache the CSS separately from the JavaScript.

  4. Build Output: All your optimized code and assets are output to a build directory in your project. This directory contains everything needed to deploy your application.

How to use react-scripts build

To create a production build of your app, you need to run the build script in your package.json. You can do this by running the following command in your terminal:

npm run build

Or, if you’re using Yarn:

yarn build

This will create a build directory in your project with all your compiled and optimized code.

For example, let’s say you have a simple React app with an App component:

import React from 'react';

function App() {
  return <h1>Hello, world!</h1>;
}

export default App;

You can create a production build of this app by running npm run build or yarn build. Then, if you look in the build directory, you’ll see your optimized and minified code ready for deployment.

Executing react-scripts test

The react-scripts test command is used to run tests in your application. It’s part of the react-scripts package, which is included in all projects created with the Create React App (CRA).

What does react-scripts test do?

When you run the react-scripts test, several things happen:

  1. Test Runner: Jest, a JavaScript testing framework, is started in watch mode. This means that Jest will automatically re-run your tests when it detects a change in your files.

  2. Interactive Mode: Jest runs in an interactive mode in the terminal. You can choose to run all tests or only a selection of tests, and you can filter by filename or test name.

  3. Code Coverage: You can also generate a code coverage report by running react-scripts test –coverage. This will tell you how much of your code is covered by tests.

How to use react-scripts test

To run your tests, you need to run the test script in your package.json. You can do this by running the following command in your terminal:

npm test

Or, if you’re using Yarn:

yarn test

This will start Jest in watch mode. Any time you save a file, it will re-run the tests.

Illustratively, let’s say you have a simple React component and a test for it:

// Component: Button.js
import React from 'react';

const Button = ({ onClick, children }) => (
  <button onClick={onClick}>{children}</button>
);

export default Button;

// Test: Button.test.js
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Button from './Button';

test('renders the correct content and responds to click event', () => {
  const handleClick = jest.fn();
  const { getByText } = render(<Button onClick={handleClick}>Click Me!</Button>);

  // Assert the button content
  expect(getByText('Click Me!')).not.toBeNull();

  // Simulate a click event
  fireEvent.click(getByText('Click Me!'));

  // Assert the onClick handler is called
  expect(handleClick).toHaveBeenCalled();
});

You can run this test by running the npm test or yarn test. Jest will run the test and report the results in the terminal.

Employing react-scripts eject

The react-scripts eject command is a part of the react-scripts package, which is included in all projects created with Create React App (CRA). This command is used when you want to customize the build configuration of your application.

What does react-scripts eject do?

When you run react-scripts eject, several things happen:

  1. Configuration Exposure: All the configuration files and scripts that were previously hidden are copied into your project. This includes configuration for Babel, Webpack, ESLint, and others.

  2. Dependency Update: The single build dependency (react-scripts) in your package.json file is removed. All the individual packages that react-scripts depend on are added to your package.json file.

  3. Irreversible Action: The eject command is a one-way operation. Once you’ve ejected, you can’t go back!

How to use react-scripts eject

To eject from the default setup, you need to run the eject script in your package.json. You can do this by running the following command in your terminal:

npm run eject

Or, if you’re using Yarn:

yarn eject

You will be prompted to confirm that you want to eject. Once you confirm, all the configuration files and scripts will be moved into your project.

For example, you have a simple React app and you want to customize the Webpack configuration. You would run npm run eject or npm eject, and then you would see a config directory in your project with a webpack.config.js file that you can customize.

Tabular Comparison of Building User Interfaces With React vs. Traditional Methods

When building user interfaces, developers have traditionally used methods like jQuery and vanilla JavaScript. However, with the advent of libraries like React, the approach to building user interfaces has seen a significant shift. Here’s a tabular comparison of building user interfaces with React versus traditional methods:

Traditional MethodsReact
ArchitectureImperative programming with DOM manipulationDeclarative components and virtual DOM
Code OrganizationSpaghetti code intermingled with HTMLLogical component structure
UI ReuseCopy and paste codeReusable components
Code ReadabilityMessy jQuery DOM manipulation and callbacksClean JSX syntax
State ManagementGlobal variables, hidden DOM valuesLocal component state and props
StylingGlobal CSS stylesheetsScoped CSS with CSS-in-JS
TestingDifficult to test disparate piecesSimple unit testing of components
Build ProcessManual concatenation and minificationAutomated with Create React App
PerformanceDOM manipulations are slowVirtual DOM minimizes DOM changes
Developer ExperienceFrustrating DOM bugs and slow buildsHot reloading and error highlighting

FAQs

What is React Script?

React Script is a set of scripts from the Create React App (CRA) project. It abstracts away the complexities of setting up build tools like Webpack and Babel, allowing you to focus on writing your application.

How do I create a React app using React Script?

You can create a new React application using React Script by running the following command in your terminal:

npx create-react-app my-app

This command creates a new directory called my-app with a boilerplate React application and all the necessary build configurations.

What is included in the React Script package?

React Script includes scripts and configurations for various tools including Babel, Webpack, ESLint, and Jest. These tools are used for transpiling modern JavaScript and JSX, bundling assets, linting code, and running tests respectively.

How do I update the React Script version in my project?

You can update React Script in your project by running the following command in your terminal:

npm update react-scripts

This command updates React Script to the latest version.

How do I eject from React Script to customize my build configuration?

You can eject from React Script by running the following command in your terminal:

npm run eject

This command exposes all the build configurations and scripts, allowing you to customize them.

What is the difference between React and ReactDOM?

React is a JavaScript library for building user interfaces, while ReactDOM provides DOM-specific methods to interact with the real DOM in a web browser. In other words, React is the heart of React applications, and ReactDOM is the glue between React and the DOM.

How do I add React to an existing JavaScript project?

You can add React to an existing JavaScript project by installing React and ReactDOM with npm and importing them into your project. Here’s how you can do it:

npm install react react-dom

Then, in your JavaScript file:

import React from 'react';
import ReactDOM from 'react-dom';

// Your React component
const App = () => <h1>Hello, world!</h1>;

// Render your React component
ReactDOM.render(<App />, document.getElementById('root'));

In the example above, we’re adding React to an existing project by installing the necessary packages and using them to render a React component.

Wrapping Up

And that’s a wrap! In this comprehensive guide, we covered all things related to react-scripts – the core of Create React App. You should now have a solid grasp of React’s ecosystem and how CRA utilizes various build tools seamlessly through react-scripts.

Building performant React apps requires mastering these underlying technologies. While CRA abstracts away the configuration, understanding what happens under the hood is invaluable should you ever need to customize it.

If you are looking to take your React skills to the next level, be sure to check out Purecode AI – a cool marketplace with ready-to-use TailwindCSS, MUI, and CSS components for your projects. You can even generate your custom UI components!

Emmanuel Uchenna

Emmanuel Uchenna

Emmanuel is an experienced and enthusiastic software developer and technical writer with 4+ proven years of professional experience. He focuses on full-stack web development. He is fluent in React, TypeScript, VueJS, and NodeJS and familiar with industry-standard technologies such as version control, headless CMS, and JAMstack. He is passionate about knowledge sharing.