DEV Community

tonybui1812
tonybui1812

Posted on

react-script, webpack and babel stuff.

Webpack and Create React App (often referred to as "react-scripts") are both tools used in web development, but they serve different purposes and have different scopes:

  1. Webpack:

    • Purpose: Webpack is a powerful and flexible JavaScript module bundler. It's used to bundle, optimize, and manage assets for a web application, including JavaScript files, CSS files, images, and more.
    • Use Cases: You typically use Webpack when you need fine-grained control over how your assets are bundled, want to set up custom build configurations, or need to bundle various types of files beyond just JavaScript.
    • Configuration: Webpack requires you to create a webpack configuration file (commonly named webpack.config.js) where you define how your assets should be processed and bundled.
  2. Create React App (react-scripts):

    • Purpose: Create React App is a tool that simplifies the process of setting up and developing React applications. It's designed to get you up and running quickly without the need for complex build configurations.
    • Use Cases: Create React App is great for beginners or for projects where you want a straightforward development setup. It abstracts away the Webpack configuration, Babel setup, and other build-related complexities.
    • Configuration: While Create React App offers some limited configuration options, it's intentionally opinionated to keep things simple. If you need more advanced customization, you may "eject" from Create React App, which exposes the Webpack configuration for further modification.

In summary, Webpack is a general-purpose module bundler and build tool that can be used for any web application, while Create React App, or "react-scripts," is a specialized tool for quickly setting up and developing React applications with a predefined, opinionated build configuration. The choice between them depends on your project's requirements and your familiarity with build tooling and configuration.

react-scripts abstracts away the Webpack configuration, Babel setup, and other build-related complexities

When we say that "react-scripts abstracts away the Webpack configuration, Babel setup, and other build-related complexities," it means that Create React App (often referred to as "react-scripts") provides a simplified and pre-configured development environment for React applications, hiding the intricate details of certain tools like Webpack and Babel from the developer.

Here's a breakdown of what this abstraction means:

  1. Webpack Configuration:

    • Webpack is a powerful but complex tool that requires a configuration file to specify how your project's assets (JavaScript files, CSS, images, etc.) should be bundled and processed.
    • Create React App comes with a pre-configured Webpack setup, so you don't need to write or understand the Webpack configuration. It has sensible defaults that work for most React projects.
  2. Babel Setup:

    • Babel is a JavaScript compiler that allows developers to write modern JavaScript (ES6/ES7) and have it transpiled into code that can run in older browsers.
    • Create React App includes a Babel configuration that supports modern JavaScript features, so you can write modern React code without worrying about configuring Babel presets and plugins.
  3. Other Build-Related Complexities:

    • In addition to Webpack and Babel, modern web development often involves various other tools and configurations for tasks like minification, hot-reloading, and code splitting.
    • Create React App abstracts these complexities by providing a sensible default setup that works well for most development scenarios. It's designed to reduce the initial learning curve and save time.

In essence, by abstracting away these complexities, Create React App allows developers to focus on writing React code and building features rather than spending time configuring and fine-tuning build tools. It's an excellent choice for beginners and for projects where a quick and hassle-free setup is desired. However, for more advanced or highly customized projects, you might need to eject from Create React App to gain direct control over the underlying build configurations.

But sooner or later, developers will need to optimize code and configuration for performance. Will react-script useful anymore?

You're absolutely right that as a project grows or requires specific optimizations, developers may find the need to customize their build configurations for performance or other reasons. In such cases, Create React App (react-scripts) may become less suitable, as its main goal is to simplify the initial setup and development experience.

Here's what developers commonly do when they need more advanced optimizations:

  1. Eject from Create React App:

    • Create React App provides a script called eject that allows you to "eject" from its simplified setup. This action reveals the underlying Webpack and Babel configurations, giving you full control.
    • After ejecting, you can modify the Webpack configuration, install additional plugins, or make other customizations to optimize the build for performance.
  2. Custom Configuration:

    • Some projects start with Create React App for the ease of setup and development and later transition to a custom configuration when specific optimizations are required.
    • In this approach, developers retain the benefits of Create React App during initial development and then gradually introduce customizations as needed.
  3. Alternative Configurations:

    • Developers can choose alternative tools or configurations from the beginning if they anticipate complex performance requirements. For example, they might set up Webpack and Babel configurations manually or use tools like Next.js or Gatsby, which offer more control over build processes.

In summary, while Create React App is excellent for getting started quickly and simplifying development, it's not a one-size-fits-all solution. Developers have options to transition to more customized build configurations when performance optimizations or other advanced requirements become necessary. This allows projects to evolve and adapt to changing needs without being limited by the initial abstraction provided by Create React App.

Top comments (8)

Collapse
 
easytony profile image
tonybui1812

What does developer usually do after eject?

Collapse
 
easytony profile image
tonybui1812

After ejecting from Create React App (CRA), developers typically take on more control and responsibility for configuring and managing their React project. Here are some common tasks that developers often perform after ejecting:

  1. Customizing Configuration: Ejected projects provide configuration files like webpack.config.js and babel.config.js. Developers can customize these configurations to meet specific project requirements, including adding custom loaders, modifying optimization settings, or integrating additional tools.

  2. Managing Dependencies: Developers are responsible for managing project dependencies, including updates. They should regularly check for updates to libraries, packages, and plugins used in their project and apply updates as needed to ensure security and stability.

  3. Adding Plugins and Loaders: Ejected projects allow developers to integrate additional Webpack plugins, Babel presets, or other tools to extend the functionality of the build process. For example, you can add a CSS preprocessor or configure code splitting.

  4. Optimizing Performance: Developers can fine-tune the production build configuration to optimize the performance of their application. This may involve techniques like code splitting, tree shaking, and lazy loading.

  5. Handling Environment Variables: CRA provides a mechanism for handling environment variables in development and production. After ejecting, developers can manage environment variables directly or use tools like Dotenv to configure environment-specific settings.

  6. Setting Up Testing: While CRA includes built-in testing tools, developers may choose to configure and customize testing frameworks (e.g., Jest, React Testing Library) further to suit their needs.

  7. Implementing Routing: If your application requires client-side routing, you may choose to set up a routing library like React Router and configure routes within your project.

  8. Styling and CSS: Developers can choose the styling approach for their application, whether it's CSS-in-JS, CSS modules, or traditional CSS. They can also add and configure styling libraries or preprocessors if needed.

  9. Adding State Management: If your application requires state management beyond React's built-in state, you may integrate a state management library like Redux or Mobx and configure it accordingly.

  10. Internationalization (i18n): If your app needs to support multiple languages, you can set up internationalization libraries and configure translations.

  11. Code Splitting: Ejected projects allow developers to implement code splitting for better performance by splitting the JavaScript code into smaller, more manageable chunks.

  12. Deployment Configuration: Depending on your deployment platform, you may need to configure deployment-specific settings, such as specifying environment variables, server settings, and hosting configurations.

  13. CI/CD Integration: Developers often set up continuous integration and continuous deployment (CI/CD) pipelines to automate testing and deployment processes.

  14. Managing Build Scripts: Review and potentially customize the build scripts defined in the package.json file to match your deployment requirements and needs.

  15. Security Considerations: Developers should follow best practices for securing their React application, including handling authentication, authorization, and protecting against common security vulnerabilities.

Ejecting from CRA provides flexibility and customization options but also adds complexity and maintenance overhead. Developers should carefully consider their project requirements and goals before deciding to eject and be prepared to invest time in configuring and maintaining their project's build and development environment.

Collapse
 
easytony profile image
tonybui1812

How to unit test my component?

Collapse
 
easytony profile image
tonybui1812

To unit test a React component, you can use testing libraries like Jest and React Testing Library. Here's a step-by-step guide on how to set up and write a unit test for a simple React component:

  1. Install Testing Libraries: If you haven't already, install Jest and React Testing Library as development dependencies:
   npm install --save-dev jest @testing-library/react @testing-library/jest-dom
Enter fullscreen mode Exit fullscreen mode
  1. Create a Test File:
    In the same directory as your component (or in a __tests__ folder within the component's directory), create a test file with a .test.js or .test.jsx extension. For example, if your component is MyComponent.js, create MyComponent.test.js.

  2. Import Dependencies:
    In your test file, import React, the testing library, and the component you want to test:

   import React from 'react';
   import { render } from '@testing-library/react';
   import MyComponent from './MyComponent'; // Import the component to be tested
Enter fullscreen mode Exit fullscreen mode
  1. Write the Test: Write a test case to render and interact with your component. Here's an example:
   test('renders MyComponent correctly', () => {
     // Render the component
     const { getByText } = render(<MyComponent />);

     // Use testing library queries to interact with the component
     const myElement = getByText('Hello, World!'); // Example: assuming your component renders text "Hello, World!"

     // Assert that the element is present in the document
     expect(myElement).toBeInTheDocument();
   });
Enter fullscreen mode Exit fullscreen mode

In this example, we're testing if MyComponent renders correctly and contains the text "Hello, World!".

  1. Run the Test: In your terminal, run the test using Jest:
   npx jest
Enter fullscreen mode Exit fullscreen mode

This will execute the tests in your project. If everything is set up correctly, you should see the test output.

If you want to run a specific test file, you can use:

   npx jest MyComponent.test.js
Enter fullscreen mode Exit fullscreen mode

Jest will run the test and report the results.

  1. Interact with the Rendered Component:
    You can use the render result to interact with the rendered component using queries provided by React Testing Library. For example, getByText, getByRole, getByTestId, etc. These queries help you find elements by text content, role, or a custom data attribute.

  2. Write More Tests:
    Write additional tests for different scenarios, edge cases, and interactions your component may have. Test different props, states, and behaviors to ensure comprehensive coverage.

  3. Assertions and Matchers:
    Use Jest's expect function and its various matchers (like .toBe(), .toBeInTheDocument(), etc.) to make assertions about your component's behavior and output.

  4. Cleanup (if needed):
    If your component sets up any side effects or subscriptions, make sure to clean them up after each test using cleanup or afterEach hooks.

By following these steps, you can set up and write unit tests for your React components using Jest and React Testing Library. This ensures that your components behave as expected and helps catch regressions when making changes to your code.

Collapse
 
easytony profile image
tonybui1812

What will developer test on react page?

Collapse
 
easytony profile image
tonybui1812

Developers typically conduct a variety of tests on a React application to ensure its functionality, reliability, and performance. Here are the types of testing that developers commonly perform on a React page:

  1. Unit Testing:

    • Component Testing: Developers write unit tests for individual React components to check if they render correctly, handle state and props appropriately, and produce the expected output. Libraries like Jest and React Testing Library are often used for component testing.
  2. Integration Testing:

    • Component Integration: Developers perform integration tests to check how different React components work together within a page or feature. They ensure that props are passed correctly, events trigger the expected behavior, and the components interact as intended.
  3. Functional Testing:

    • End-to-End (E2E) Testing: Developers conduct E2E tests to simulate user interactions with the application. Tools like Cypress or Selenium are used to automate interactions like clicking buttons, filling forms, and verifying that the application behaves correctly from a user's perspective.
  4. State Management Testing:

    • Redux Testing: If the application uses Redux or another state management library, developers write tests to verify that state changes, actions, and reducers function as expected.
  5. Routing Testing:

    • React Router Testing: For applications with client-side routing using React Router, developers test route navigation and ensure that the correct components render for different URLs.
  6. API Testing:

    • API Integration Testing: Developers test interactions with backend APIs to validate that data is fetched, sent, and processed correctly. Tools like Axios, fetch, or mock APIs can be used for this purpose.
  7. Performance Testing:

    • Performance Profiling: Developers use profiling tools (e.g., React DevTools, Chrome DevTools) to analyze and optimize the rendering and performance of components. They look for performance bottlenecks and optimize rendering to achieve smoother user experiences.
  8. Accessibility Testing:

    • Accessibility (a11y) Testing: Developers check that their React components meet accessibility standards (e.g., WCAG) to ensure that the application is usable by individuals with disabilities. Tools like Axe, pa11y, or manual testing with screen readers are commonly used for a11y testing.
  9. Cross-Browser Testing:

    • Cross-Browser Compatibility: Developers test their React application in multiple web browsers (e.g., Chrome, Firefox, Safari, Edge) to ensure that it works correctly and looks consistent across different browser environments.
  10. Responsive Design Testing:

    • Responsive Design: Developers verify that the application's layout and user interface elements respond appropriately to various screen sizes and devices. They use tools like browser developer tools and real devices or emulators for testing.
  11. Security Testing:

    • Security Scanning: Developers conduct security assessments to identify and address vulnerabilities in their React application. They look for common security issues such as Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF).
  12. Load Testing:

    • Load and Performance Testing: In preparation for production deployment, developers may perform load testing to assess how the application performs under heavy traffic. Load testing tools like Apache JMeter or Locust can help simulate high loads and monitor server response times.
  13. Error and Exception Testing:

    • Error Handling: Developers test error scenarios and exceptions to ensure that the application gracefully handles unexpected situations and provides appropriate error messages to users.
  14. User Acceptance Testing (UAT):

    • User Testing: In addition to developer testing, developers often involve end-users or stakeholders in user acceptance testing to gather feedback and ensure that the application meets user expectations.

Testing is an essential part of the development process, helping identify and fix issues early in the development lifecycle. The specific tests you perform will depend on your application's complexity, requirements, and the quality standards you aim to achieve.

Collapse
 
easytony profile image
tonybui1812

How project folder look like after eject?

Collapse
 
easytony profile image
tonybui1812

After ejecting a Create React App (CRA) project, your project folder will undergo some changes. The folder structure will include new configuration files and scripts, giving you greater control over your project. Here's how the project folder typically looks after ejecting:

- my-react-app/  (Your project's root directory)
  - config/      (Configuration files)
    - env.js
    - paths.js
    - webpack.config.js     (Webpack configuration)
    - webpackDevServer.config.js
  - node_modules/ (Node.js modules, including build scripts)
  - public/       (Public assets and HTML template)
    - index.html
    - favicon.ico
  - scripts/      (Custom scripts for building and running the app)
    - build.js
    - start.js
    - test.js
  - src/          (Your application source code)
    - App.js
    - index.js
    - ...
  - .gitignore    (Git ignore file)
  - package.json  (Project dependencies and scripts)
  - README.md     (Project documentation)
  - yarn.lock     (Yarn lock file, if using Yarn)
Enter fullscreen mode Exit fullscreen mode

Here's a brief description of the key folders and files:

  • config/: This folder contains various configuration files used by Webpack and other build tools. You can customize these files to modify your project's build and development settings.

  • node_modules/: This directory stores all of your project's dependencies, including the development dependencies needed for building and running the project.

  • public/: This directory contains public assets such as index.html (the HTML template for your app) and any other static files you want to include in your project.

  • scripts/: This folder contains custom scripts used for building and running your app. You can modify these scripts to suit your needs.

  • src/: This is where your application source code resides. You'll find your React components, styles, and other application-specific files here.

  • .gitignore: This file specifies which files and directories should be ignored by Git when you commit changes to version control.

  • package.json: This file lists your project's dependencies and contains custom scripts defined for your project.

  • README.md: This is the README file for your project, where you can document important information about your app.

  • yarn.lock (optional): This file is generated when using Yarn for dependency management. It helps ensure consistent installations of packages.

After ejecting, you have the flexibility to customize your project's build process, but you're also responsible for managing the configuration and updates. Make sure to review the newly generated files and understand their purpose before making any customizations.