How to set React Custom Port like 3129 - reactjs

My project is based on create-react-app. npm start or yarn start by default will run the application on port 3000 and there is no option of specifying a port in the package.json.

Just update a bit in webpack.config.js:
devServer: {
historyApiFallback: true,
contentBase: './',
port: 3000 // <--- Add this line and choose your own port number
}
then run npm start again
This will set the default port for that app to the on you specified
Alternatively:
modify part of package.json from:
"start": "react-scripts start"
for Linux and MacOS to:
"start": "PORT=3006 react-scripts start"
Windows to:
"start": "set PORT=3006 && react-scripts start"

With create react app, you can create a file called .env at the root level, and put the following code inside it :
PORT=3129

Add .env file in source folder and add entry like below
PORT=9001

run this code
yarn start --port 30022

Related

Craco build fails, taking aliased folder as external package

I'm using craco and craco-alias to implement aliases for imports in my Create React App project.
Followed instructions in https://github.com/gsoft-inc/craco/blob/master/packages/craco/README.md#installation and https://github.com/risenforces/craco-alias#readme
I configured package.json to use craco instead of react-scripts for starting dev server, tests and production build
...
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"lint:css": "stylelint './src/**/*.css'",
"lint:js": "eslint 'src/**/*.js'",
"test:w": "craco test --watch",
"postinstall": "patch-package"
},
...
Then I created jsconfig.json file w aliases paths
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"#components": ["components/*", "components"],
"#constants": ["constants/*", "constants"],
"#assets": ["assets/*", "assets"],
"#store": ["store/*", "store"],
"#utils": ["utils/*", "utils"]
},
"include": ["src"],
"exclude": ["node_modules", "build", "coverage"]
}
And craco.config.js file, which uses craco-alias plugin
/* craco.config.js */
const CracoAlias = require('craco-alias');
module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
baseUrl: './src',
source: 'jsconfig',
}
}
]
}
Now I'm using aliases for imports in my app like this
// root index.js file
...
import Layout from '#components/Layout';
import store from '#store'; // this line causes error on CI build
function App() {
return (
<Layout>
/* inner components */
</Layout>
);
}
Everything works fine (aliased imports works on dev-server, in jest tests and even if I serve locally built project) until I push it to github repo. That repo has configured github actions to build and test project on remote server and it fails with error on build step, after installing all packages.
Run yarn build
yarn run v1.22.4
$ craco build
Creating an optimized production build...
Browserslist: caniuse-lite is outdated. Please run next command `npm update`
Failed to compile.
./src/index.js
Cannot find module: '#store'. Make sure this package is installed.
You can install this package by running: npm install #store.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
##[error]Process completed with exit code 1.
Could somebody help me understand what wrong with my code? Why craco or webpack expect '#store' to be external package instead of aliased import of internal module?
In my case problem wasn't in craco or webpack, but in my previous actions and OS filesystem differences. I'm using Windows 10 and WSL in VS Code terminal. So before I use '#' symbol for aliases I tried to use CamelCase for my folders and renamed it via windows explorer (because for me it was simpler to close VSCode and rename files via explorer than to open new bash terminal in new VSCode window after closing opened files).
Then I prefer to use '#' symbol and rename folders back to lowercase. I configured aliases and pushed changes to remote github repo, where CI actions were run. When CI was running actions it can't find 'store' folder (because previously I renamed it to 'Store' and it was last saved path to folder in git), so it tried to find external package named 'store'.
To fix this I change git config to stop ignoring namecasing for my folder by running command git config core.ignorecase false. Git history was updated, I push it to remote repo and CI actions succeeded.

define .env file except default env file in react app

I need to load for each development/production server a different .env file.
localhost | .env.localhost
development | .env.development
production | .env.production
base on react documentation, by default we can use .env.development and .env.production
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
but i want to use new environment variable as localhost. how can i do that? i want to run one of my script by .env.localhost variable's file.
you can modify script part of package.json from:
"start": "react-scripts start"
for Linux and MacOS to:
"start": "PORT=3006 react-scripts start"
Windows to:
"start": "set PORT=3006 && react-scripts start"
And if you want to set new variables in environment. Then add then in .env files of shell, but start name with REACT_APP for ex
REACT_APP_MY_VAR

create react app not picking up .env files?

I am using create react app to bootstrap my app.
I have added two .env files .env.development and .env.production in the root.
My .env.development includes:
API_URL=http://localhost:3000/api
CALLBACK_URL=http://localhost:3005/callback
When I run my app using react-scripts start and console out process.env it spits out
{ NODE_ENV: "development", PUBLIC_URL: "" }
I've tried different things, but its just not picking up the veriables in my development file, what am I doing wrong?!
Directry structure is:
/.env.development
/src/index.js
Package.json script is:
"start": "export PORT=3005; npm-run-all --parallel server:start client:start",
"client:start": "export PORT=3005; react-scripts start",
"server:start": "node server.js",
"build": "react-scripts build",
Edit:
#jamcreencia correctly pointed out my variables should be prefixed with REACT_APP.
Edit 2
It works okay if I name the file .env but not if I use .env.development or .end.production
With create react app, you need to prefix REACT_APP_ to the variable name. ex:
REACT_APP_API_URL=http://localhost:3000/api
REACT_APP_CALLBACK_URL=http://localhost:3005/callback
** Make sure your .env file is in the root directory, not inside src folder.
CRA Docs on Adding Custom Environment Variables:
Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name
Make sure your .env file is in the root directory, not inside src folder.
Had this same problem! The solution was to close the connection to my node server (you can do this with CTRL + C). Then re-start your server with 'npm run start' and .env should work properly.
Source: Github
If you want to use multiple environment like .env.development .env.production
use dotenv-cli package
add .env.development and .env.production in project root folder
and your package.json
"scripts": {
"start": "react-app-rewired start",
"build-dev": "dotenv -e .env.development react-app-rewired build",
"build-prod": "dotenv -e .env.production react-app-rewired build",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom",
"eject": "react-scripts eject"
},
then build according to environment like
npm run-script build-dev
I was having the same problem, but it was because I had my .env file in YAML format instead of JS.
It was
REACT_APP_API_PATH: 'https://my.api.path'
but it needed to be
REACT_APP_API_PATH = 'https://my.api.path'
For people who apply all those answers above and didn't work just restart the terminal of npm start, stop the live server and run it again and it will work because it works for me
Regarding env-cmd. As per VMois's kind post on gitHub, env-cmd has been updated ( version 9.0.1 as of writing ), environment variables will work as follows on your React project:
"scripts": {
"build:local": "env-cmd -f ./.env.production.local npm run build",
"build:production": "env-cmd -f ./.env.production npm run build"
}
In your package.json file.
1- Make sure .env file is based your react app root directory
2- for react app you need to prefix REACT_APP_ to the variable name. ex: REACT_APP_API_URL
3- kill server and npm start again after .env file modify
For this purpose there is env-cmd module. Install via npm npm i env-cmd then in your package.json file in scripts section:
"scripts": {
"start": "env-cmd .env.development react-scripts start",
"build": "GENERATE_SOURCEMAP=false env-cmd .env.production react-scripts build",
}
In your project root you have to create two files with the same env variables but with different values:
.env.development
.env.production
Then exclude them from public. For this in your .gitignore file add two lines:
.env.development
.env.production
So this is a proper way to use different env variables for dev and prod.
While working with .env file, be it frontend or backend.
Whenever you modify the .env file, you must restart the respective server for the changes to take effect in the application.
Hot reloading doesn't read changes from .env file.
If the .env file works but .env.development or .env.production don't, then create an empty .env file alongside those two. I don't know why but this works for me.
Your project can consume variables declared in your environment as if they were declared locally in your JS files. By default you will have NODE_ENV defined for you, and any other environment variables starting with REACT_APP_.
Reference: https://create-react-app.dev/docs/adding-custom-environment-variables
that doc creates confusion.
So you actually need to put prefix REACT_APP_ within the .env to make it work.
And make sure that you restart the test/dev/prod server because the .env content change was loaded on the build stage.
And remember not to have semi-colon after the API key in the env-file.
REACT_APP_API_KEY = 'ae87cec695cc4heheh639d06c9274a';
should be
REACT_APP_API_KEY = 'ae87cec695cc44heheh1639d06c9274a'
that was my error
when you get undefined from the environment file then just stop the terminal and restarts with npm start command.
For any VS Code users, be aware that the .env.local env file is auto-sourced, but also auto-ignored from search results when you do a project wide search for MY_ENV_VAR(probably due to it being git ignored by default). This means that if you have MY_ENV_VAR= in your .env.local like me and forgot about it, it'll break things and you'll spend 15 mins being very confused.
Was struggling for a good hour before I noticed my kind IDE added an import:
import * as process from "process";
just remove it and you're fine, if that's your case as well.
After you add .env file, you need to
restart your application
kill the server
run npm start again
And it should work
I had same issue that I wasn't able to access .env variable in App.js.
and I had solved the problem use create correct .env file.
in my case I was copy file from different OS and use in ubuntu system
so just I did "sudo touch .env" and added my variables and restart app again then it's working for me.
I forget to add process.env.
It looks like this
const domain = process.env.REACT_APP_AUTH0_DOMAIN;
first step:
in your .env.local file add REACT_APP_your_API_key in this way
second step:
Add your config file ${process.env.REACT_APP_Your_API_key}
the third step:
must restart your React App and then Test whether it works.
mainly, I forget the last step
If none of the solutions above worked for you, give these potential solutions a shot:
Make sure all the import statements within the file that is requiring defined environmental variables are being imported from the local project and not some other project(VSCode wrongly autocompleted some of my import statements in this manner)
Try exiting your current Terminal instance and running the app in a new instance
I made the silly mistake of naming my file secret.env because that's how I always did it in Node.js.
After changing the name to .env, restarting the terminal, and running npm start again, everything worked like a charm
I didn't get any value back as well. For some reason, I thought the environment file should be dev.env, qa.env etc. Actually, it's just ".env". That's that. In case some else makes this mistake.
create-react does not supports hot reload feature .env files since they are not Javascript. So, when you change the env files make sure to manually start your server to see the effect of new changes.
In my case, a manual restart of the server worked fine :)
What worked for me was to install env-cmd and after that in my package.JSON add the following line of code
"scripts": {
"start": "env-cmd -f .env.development react-scripts start ",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
As of latest react-scripts (3.2.0) it's a simple as putting say
PORT=4000
BROWSER=none
in your .env or .env.development file (..etc) which is supposed to be in the root folder.
It will NOT work with then REACT_APP prefix (the docs are outdated I guess) and it does NOT require any extra npm packages (react-scripts already includes dotenv 6.2.0)

Auto reload react server on update

I'm new to React. I'm having some problems with react server. After starting the server by npm start if I work on the source code and make some changes, I have to stop the server and restart it to make that change available on the browser. Is there anyway to make it auto compile and refresh the browser on update ? (Like nodemon for node ?)
I had a similar (or event the same) problem and I changed starting command in the package.json file by adding following flags: --watch --watch-poll to the webpack-dev-server:
{
//...
"scripts": {
"start": "webpack-dev-server --env.ENVIRONMENT=development --content-base src/ --mode development --watch --watch-poll",
// ...
}
// ...
}
Now, using npm start and then changing src files I can see changes in the browser.
Please here https://webpack.js.org/configuration/watch/ for more options.

React tutorial - how do I start the node server for a reactJs application?

I'm just starting the react.js tutorial, I've downloaded the files and then it mentions:
"Follow your progress by opening http://localhost:3000 in your browser (after starting the server). "
I know this may sound stupid, (bear with me since I'm a beginner with React) but how do I start the server in this instance?
Thanks.
Marc
Pretty solid chance it's npm start from the project root.
Properly packaged modules will have some node scripts configured in package.json. It's customary to use start as the script to run the dev environment, though some might use build, dev, or other names.
Here's official installation process: link, and officially recommended tutorials
# install react cli
npm install -g create-react-app
# create app
create-react-app my-react-app-name
# go to project folder
cd my-react-app-name
# install dependencies
npm install
# start live server
npm start
output:
$ You can now view my-react-app-name in the browser.
$ Local: http://localhost:3000/
$ On Your Network: http://192.168.0.105:3000/
$ Note that the development build is not optimized.
$ To create a production build, use npm build.
You can run any one of the below mentioned commands to start the node server for your ReactJS application:
npm run-script start
npm run start
npm start
All the above commands are equivalent but people prefer the third one as it is the shortest to type on keyboard.
The start parameter in these commands maps to the start key present under scripts configuration present in package.json file of any ReactJS application. Here is a sample package.json file of my hello-world application:
{
"name": "hello-world",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2"
},
"devDependencies": {
"react-scripts": "0.9.5"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
You can see that react-scripts start is written in front of start key. So react-scripts start command will get fired when we run any of the three commands which I had enlisted in the beginning e.g. npm start.
I used Node to run the server. The steps I followed are:
I downloaded the zip package from the Running a server section
here
I had the link open: http://localhost:3000/
I opened up Node.js Command Prompt and navigated to the downloaded
zip project. From Node example here:
Just type the commands in the example:
First npm install and then
node server.js.
See the screen shot below:
When I refresh the localhost web page I see the following:
Sounds like you're following the official React tutorial, in which case the instructions to start the various included server implementations are here.

Resources