How to make create-react-app auto build?
Unfortunately this is something you will have to do yourself. You can use a tool like npm-watch to accomplish what you want though:
Install npm-watch
npm i --save-dev npm-watch
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/" }}
Afterwards, just use npm run watch
to start up npm-watch so it can rebuild your assets on changes.
Update:
React-scripts now includes a proxy
option that proxies requests to a different host/port. For example, if your backend is running on localhost
at port 9000
under the /api
route, then you would add this line to your package.json: "proxy": "localhost:9000/api"
. You could then make requests as you normally would in production. (source: https://create-react-app.dev/docs/proxying-api-requests-in-development)
While this doesn’t really answer your question, you shouldn’t be using npm run build
in development. Not only the rebuilds are slow, but it also skips important React warnings for performance and size, so you’ll end up scratching your head more and getting a lot less details in the warnings.
If you just need to do API requests with Express, use the proxy
feature which lets you proxy API requests from npm start
to your server. There is also a tutorial with a matching repository demonstrating how to do that.
In production, of course, you should use the build produced by npm run build
. But you would only need to run it before deployment.
Run your backend on a different port. If your running on express modify the file bin/www
var port = process.env.PORT || 9000
and in your /src folder create a config file where you configure your api host,routes, params etc
//config/index.jsexport const Config = { protocol: 'http', host: window.location.hostname, //or the environment variable params: '/api/', api: {post:'/posts/'}}
and in your calling component or where ever your calling the api's
import {Config} from '../config'axios.get(`${Config.protocol}${Config.host}${Config.params}${Config.api.posts}${some id i guess}`)