What are the steps to set up auto-building with create-react-app?

I've been utilizing create-react-app for some time now. Autoreloading with 'npm start' or 'yarn start' has been working well on its own, but now I'm facing another issue. Currently, I am running the app on an Express server through the build folder and using 'npm run build' since Express serves the built files. There are numerous API calls that require the app to be executed in this manner. It has become tedious to manually run 'npm run build' every time. Is there a simple solution or workaround to automatically build like 'npm start' without ejecting the app (I know I could eject and configure webpack to achieve this, but I'd prefer not to pursue that route)? Thanks

Answer №1

Regrettably, this task must be completed by you personally. However, you can utilize a tool like npm-watch to achieve your goal:

How to Install npm-watch

npm i --save-dev npm-watch

Details in package.json

{
  "name": "react-app",
  "version": "0.1.0",
  "private": false,
  "devDependencies": {
    "npm-watch": "^0.1.8",
    "react-scripts": "0.9.5",
  },
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "watch": "npm-watch"
  },
  "watch": {
    "build": "src/"
  }
}

Simply run npm run watch after installation to initiate npm-watch for automatic asset rebuilding upon modifications.

Update Information:

An alternative is available as React-scripts now offers a proxy option for routing requests to another host/port. For example, if your backend operates on localhost at port 9000 within the /api route, add this line to your package.json: "proxy": "localhost:9000/api". This simplifies request handling during production. (source: https://create-react-app.dev/docs/proxying-api-requests-in-development)

Answer №2

Although this may not directly address your query, it is advisable to avoid using npm run build during development. Running this command can slow down the rebuild process and omit important React warnings related to performance and size, leading to confusion and lack of detailed information in the warnings.

If you simply require API requests with Express, consider utilizing the proxy feature which allows you to proxy API requests from npm start to your server. Additionally, there is a helpful tutorial along with a corresponding repository showcasing how to achieve this setup.

In a production environment, it is recommended to utilize the build generated by npm run build. Nevertheless, this command should only be executed prior to deployment.

Answer №3

To change the port your backend is running on, adjust the settings in the bin/www file if you're using Express.

var port = process.env.PORT || 9000

Create a configuration file in your /src folder to set up your API host, routes, parameters, and more.

//config/index.js
export const Config = {
   protocol: 'http',
   host: window.location.hostname, //or use an environment variable
   params: '/api/',
   api: {post:'/posts/'}
}

In the component where you are making API calls, import the Config file and make your requests.

import {Config} from '../config'

axios.get(`${Config.protocol}${Config.host}${Config.params}${Config.api.posts}${some id i guess}`)

Answer №4

One simple method I discovered (as of 10/19/21) is employing cra-build-watch. It functions flawlessly.

Answer №5

When using create react app, I made some modifications to the scripts for running the project in development mode on Windows, building the production version, and running the production build.

"scripts": {
    "start": "set PORT=8080 && react-scripts start",
    "build": "react-scripts build",
    "deploy": "set PORT=8008 && serve -s build"
  }

To run the project in development mode on Windows, use npm start. To build the production version, use npm run-script build. And to run the production build, use npm run-script deploy.

  • Before running npm run-script deploy, make sure to install serve globally with npm install -g serve.

Answer №6

Step 1: Install create-react-app globally by running the command npm install create-react-app -g

Step 2: Create a new React app by running create-react-app Your_Apps_Name

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating multiple layouts in Next.js based on your project's needs is a common practice. Let's explore

I have been working on the following starter project: https://github.com/vercel/nextjs-subscription-payments The default content provided in the above link serves as the home page for my project. Now, I am looking to create an admin and dashboard section ...

Unable to Transmit Authorization Header in Cross-Domain Access Situation

My Node.js server has cross-origin communication enabled, allowing my Vue application to access its API from a different origin where static assets are served. This is achieved by setting the following code in Node.js: res.setHeader('Access-Control-Al ...

The ajax code is failing to retrieve the data from the table and populate it in the

hi guys i have an issue on ajax. where ajax can't work to take the data of second rows. This's code in model function getdtbarang($barcode = FALSE) { if ($barcode === FALSE) { $query = $this->db1->get(&a ...

Can one initiate a server within Zapier Code?

Is there a way to send an HTTP CODE = 200 with a response body of 'OK' when receiving a notification on Zapier? I attempted to use the following code snippet in Zapier: var http = require('http'); const server = http.createServer((r ...

Interacting with shadow DOM elements using Selenium's JavaScriptExecutor in Polymer applications

Having trouble accessing the 'shop now' button in the Men's Outerwear section of the website with the given code on Chrome Browser (V51)'s JavaScript console: document.querySelector('shop-app').shadowRoot.querySelector ...

the hidden input's value is null

I am encountering an issue with a hidden input in this form. When I submit the form to my API, the value of the input is empty. Isbn and packId are both properties of a book model. However, for some reason, the value of packId is coming out as empty. & ...

When utilizing Material-UI GridListTile within a component in React, the style attributes may be lost

In my UI, I display a <GridList> with custom component tiles that I created. Initially, I was confused about React hooks and prop passing, so I was treating it like a regular JS function: const VideoTile = ({...props}) => { const { url, class ...

I am encountering difficulties displaying the image and CSS files from another folder in my HTML with Node.js

I am facing difficulty in establishing a connection between my front-end and back-end using node.js. As a result, the website only displays the HTML code without linking to the CSS or image files. Here is the folder structure: root -src •pi ...

Utilize resources from webpack's bundled npm package assets

I've been racking my brain over this issue for quite some time now, and I'm starting to wonder if it's even achievable. Any assistance on this matter would be greatly appreciated! The npm dilemma I have an npm package that serves as a coll ...

Methods like jQuery blink(), strike(), and bold() offer dynamic ways to manipulate

I'm currently tackling an inquiry. The code I crafted seems to be functioning without any issues: (function () { if($('#target:contains("bold")')) { $('#target span:first').css('font-weight','bold ...

Having trouble with Express Get Routes - keeps showing 404 error

I am encountering an issue with my basic node express application. The root route loads fine, but additional routes such as /about or /services are not working correctly. Even though I can change the EJS template for the homepage and it renders properly, ...

How to utilize a parameter value as the name of an array in Jquery

I am encountering an issue with the following lines of code: $(document).ready(function () { getJsonDataToSelect("ajax/json/assi.hotel.json", '#assi_hotel', 'hotelName'); }); function getJsonDataToSelect(url, id, key){ ...

Toggle the visibility of the identical div

I am facing a challenge with dynamically hiding and showing various div elements on my website. I have managed to achieve this using show/hide, but the issue arises when I need to show/hide some of the same fields repeatedly. The script works fine on the f ...

What could be the reason for Jest's failure to execute tests involving npm packages?

I recently started a new project using the create-react-library package. In an attempt to add unit tests with Jest and Enzyme, I encountered an issue. While my test functions properly for a basic component, it fails when trying to test a component that inc ...

While the Navbar component functions properly under regular circumstances, it experiences difficulties when used in conjunction with getStaticProps

https://i.stack.imgur.com/zmnYu.pngI have been facing an issue while trying to implement getstaticprops on my page. Whenever I try to include my navbar component, the console throws an error stating that the element type is invalid. Interestingly, I am abl ...

Attempting to execute a PHP script through a JavaScript if statement

I have a form that requires validation with JavaScript. In one of the if statements, after all other conditions have been validated, I want to execute my PHP script that updates an SQL database with one of the passwords. Here is the final validation code: ...

Vue - unable to display component CSS classes in application when using class-style bindings

Just diving into Vue and starting with class-style binding syntax. I'm facing an issue where the CSS classes for header and footer that I've defined are not displaying, even though I've referenced them in the component tags. Can't seem ...

Steps to resolve eslint error in cases of using the node: protocol for importing Node.js built-in modules

Can someone guide me on what to include in my .eslintrc file for my specific situation? Link 1 Link 2 If I disable this rule, I encounter the following error: import path from "path"; // ESLint: Prefer `node:path` over `path`.(unicorn ...

Dealing with the challenges posed by middleware such as cookie access and memory leaks

Utilizing express with cookieParser() where my client possesses the cookie named: App.Debug.SourceMaps. I've crafted a middleware as follows: app.get('/embed/*/scripts/bundle-*.js', function(req, res, next) { if (req.cookies['App ...

Ways to Export HTML to Document without any borders or colorful text

How can I make a contentEditable area visible when filling text and then disappear when exporting the document? I found a script online that allows you to do this, but the issue is that the contentEditable area is not visible until clicked on. To address t ...