What would be the process of setting up ENV variables to work in your react project when your react project isn't built using create-react-app, and has no backend?
Found the answer. Quoted from this post by Aminu Kano.
Webpack Users
If you are using webpack, you can install and use
dotenv-webpack plugin, to do that follow steps below:
Install the package
yarn add dotenv-webpack OR npm i dotenv-webpack
// .env
API_KEY='my secret api key' Add it to webpack.config.js file
// webpack.config.js const Dotenv = require('dotenv-webpack');
// webpack.config.js
const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv()
]
...
};
Use it in your code as
process.env.API_KEY
For more information and configuration
information, visit here
Step 1:
yarn add dotenv-webpack
Step 2: on webpack.config.js file:
const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv()
]
...
};
Last step: create .env file & put system variable in it:
URL=something.com
I think you can you a .bashrc file in linux to add any environment variable you want to use in the program.
Variable=<value>
you can just add variables and corresponding values and then you save and source the bashrc file using source abc.bashrc and then those variables will be available in the envrionment for the current terminal.
You can use this file in any programming language where you can read the environment variables.
Related
Is it possible to set environment variables in the manifest.json file of a Chrome Extension?
Like wOxxOm said, I used webpack to proccess manifest.json.
In my case, I needed to set version automatically on manifest file.
I added to webpack script:
plugins: [
new CopyWebpackPlugin([
{
from: "public/manifest.json",
to: "manifest.json",
transform(content, path) {
return modify(content)
}
}
]),
]
And the modify function replaces version on file for the parameter:
function modify(buffer) {
var manifest = JSON.parse(buffer.toString());
let argv = process.argv[2];
if (argv) manifest.version = argv.split("=")[1];
let manifest_JSON = JSON.stringify(manifest, null, 2);
return manifest_JSON;
}
So, I build like "yarn build --version=x.x" and webpack do what I need.
PS: if you're going to use this, remember to change:
the manifest.json directory, if necessary;
the value in the modify function, in my case it was version
As the OP has mentioned in her answer, using the copy-webpack-plugin in the webpack.config.js file is the way to go if you're building your Chrome Extension with React. However, if your React app is based on create-react-app, directly editing the webpack.config.js file (which is located in node_modules/react-scripts/config) is not recommended.
In such a case, use craco, which is an npm package that can be used to customize an app based on create-react-app. Here's how you do it:
Install craco into your project using npm i #craco/craco.
Install copy-webpack-plugin as a dev-dependency in your project using npm i --save-dev copy-webpack-plugin.
Let's suppose we're creating a development and a production build of our Chrome Extension. Let's also suppose we've already assigned "version": "0.1.0" in our Chrome Extension's manifest.json. Depending on the build type, we'd like to assign accordingly the version_name field in our Chrome Extension's manifest.json, e.g., "version_name": "0.1.0 dev" for development and "version_name": "0.1.0" for production. In your React app's package.json, introduce two fields (the script names can be whatever you wish) as follows:
"scripts": {
...
"build-dev": "CRX_ENV=dev craco build", // or "set CRX_ENV=dev&& craco build" in the case of Windows
"build-prod": "CRX_ENV=prod craco build", // or "set CRX_ENV=prod&& craco build" in the case of Windows
...
}
Create a new file called craco.config.js in the root of your project. As per your need, do something similar to the following in the craco.config.js file:
const CopyPlugin = require("copy-webpack-plugin")
module.exports = {
webpack: {
plugins: [
new CopyPlugin({
patterns: [
{
from: "public/manifest.json",
to: "manifest.json",
transform(content, path) {
return modifyManifest(content)
},
},
],
}),
],
},
}
function modifyManifest(buffer) {
const manifest = JSON.parse(buffer.toString())
if (process.env.CRX_ENV === "dev") {
manifest.version_name = `${manifest.version} dev`
} else if (process.env.CRX_ENV === "prod") {
manifest.version_name = `${manifest.version}`
}
const manifestJson = JSON.stringify(manifest, null, 2)
return manifestJson
}
Run npm run build-dev. It will create a folder called build in your project root. This build folder is your unpacked Chrome Extension, which you can load into Chrome using the "Load unpacked" button on the chrome://extensions page. Once loaded, you should be able to see 0.1.0 dev as the version name of your Chrome Extension.
Delete the build folder created from the previous step and run npm run build-prod, and repeat the same steps. You should be able to see 0.1.0 as the version name of your Chrome Extension on the chrome://extensions page.
I'm working on ReactJS and trying to read some configs from .env file.
I follow instruction from this page but it doesn't work for me.
Here is my Test.js:
import React from 'react';
require('dotenv').config()
class Test extends React.Component {
constructor(props) {
super(props);
this.state={
user:process.env.DB_USER,
pass:process.env.DB_PASS
}
}
render() {
return (
<div>
<p>Test</p>
{this.state.user}
{this.state.pass}
</div>
);
}
}
export default Test;
Here is my .env file:
DB_USER=test
DB_PASS=test
Here is my folder structure:
On my page I get only the text: "Test". So I think the app cannot get the value from .env file.
Is there anyone here can help me to read configs from .env file? Thank you in advanced.
Assuming that you use create-react-app for your project boilerplate. You can just add REACT_APP prefix to your env variables. First, create a .env file at your root directory (outside src folder). In your .env file
REACT_APP_USERNAME=lorem
then you can call it anywhere in your project by using process.env.REACT_APP_USERNAME, for example
console.log(process.env.REACT_APP_USERNAME)
I hope this works and good luck
1) ReactDocs If you use create-react-app as boilerplate
1.1 #.env file
REACT_APP_SOME_NAME=something
Name MUST start with REACT_APP_
1.2 Access ENV variable
<p>{process.env.REACT_APP_SOME_NAME}</p>
1.3 npm run start
Restart application after adding variable in .env file using npm run start
2) If not using create-react-app
2.1) npm install dotenv --save
2.2) Next add the following line to your app.
require('dotenv').config()
2.3) Then create a .env file at the root directory of your application and add the variables to it and restart application after adding variables using npm start.
// contents of .env
REACT_APP_API_KEY = 'my-secret-api-key'
2.4) Finally, add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub.
Assuming that you're running your app from the root directory of the project, my understanding is that you'll need to specify the path of the .env file as src like this:
const dotenv = require('dotenv');
/* Specify path to .env file */
dotenv.config({ path: 'src' });
I want to store variable in .env variable and use it like process.env
I added .env file in root directory
REACT_APP_FOO = abcc111
webpack.config.dev.js
plugins: [
new webpack.ProvidePlugin({
React: 'react'
}),
new webpack.DefinePlugin({
"process.env":{
'REACT_APP_FOO': JSON.stringify(process.env.REACT_APP_FOO)
}
})
],
App.js
console.log(process.env);
Result is:
{REACT_APP_FOO: undefined}
Please let me know if i am missing anything here.
Steps to add .env contents
1) npm install dotenv --save
2) At top of webpack config file
const dotenv = require('dotenv').config({path: __dirname + '/.env'});
3) Then create a .env file at the root directory of your application and add the variables to it.
//contents of .env
REACT_APP_FOO = abcc111
4) webpack config file
new webpack.DefinePlugin({
"process.env": dotenv.parsed
}),
4) Add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub. Need to restart application after adding variable in .env file.
If you are using create-react-app, it uses react-scripts which has dependency of dotenv so you don't have to install and configure, you could just create .env file and use in your application.
Convention being name should start with REACT_APP
Hope that helps!!!
Saleor Storefront using EnvironmentPlugin of webpack
Like
new webpack.EnvironmentPlugin(["npm_package_version", "BACKEND_URL"])
My .env file
# .evn
npm_package_version = 6.4.1
BACKEND_URL = https://demo.getsaleor.com
In my Index file
console.log("env",process.env.BACKEND_URL) is undefined
On start project as development Log
WARNING in EnvironmentPlugin - BACKEND_URL environment variable is undefined.
I set Default value like this
new webpack.EnvironmentPlugin({'BACKEND_URL': 'https://demo.getsaleor.com'})
This is working fine but i need to get value from .env file
Please help me solve this problem
.env files are not picked up by themselves. You need to use a package in order to specify the file in which you've defined your environment variables.
You can use dotenv for nodejs and DotenvPlugin for webpack in order to expose your environment variables through .env file.
DotenvPlugin for webpack
dotenv package for nodejs
Hope this helps. Happy coding !
create-react-app is supposed to inject your .env variables into your React app. I have used the REACT_APP_ prefix with my variables in my .env and .env.development.
However, when debugging the code I've found that process itself is undefined. So when trying to access an environment variable with process.env.REACT_APP_SOMETHING_URL, the root process variable is undefined.
So at the time I misunderstood how process.env works in create-react-app. I expected this to be available at runtime. However, because React is a frontend library and process is a Node backend entity you cannot directly access process.env while executing code in the browser.
This makes sense because in-browser executed Javascript doesn't know about Node; therefore, process.env isn't available.
What happens instead is that during a webpack build, webpack will inject the corresponding environment variables into your frontend asset code. So if you have a production .env file, those variables are provided during the build.
$ yarn add --dev react-app-env
or
$ npm install react-app-env --save-dev
well let me begin by saying process is an eventEmitter what lives in the nodejs world if you log it in a browser, no matter if it is angular, CRA, Vue, jquery all of them will print undefined because in the context of a browser it does not exist.
now on a CRA you is able to use process.env.YOW_VAR, basically bcuz CRA creates an Obj call process.env that is the reason behind why you need to add a prefix to them env vars which I think is REACT_APP.
const YOW_VARS = Object.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce(
(env, key) => {
env[ key ] = process.env[ key ];
return env;
},
{
NODE_ENV: process.env.NODE_ENV || 'development',
}
);
const s = {
'process.env': Object.keys(YOW_VARS).reduce((env, key) => {
env[ key ] = JSON.stringify(YOW_VARS[ key ]);
return env;
}, {}),
};
more or less they have something like that
The react-app-env package suggested on another post on this page is deprecated, as described in its repo: https://github.com/tuchk4/react-app-env
I recommend using dotenv instead.