display the current npm version of my NodeJs app - reactjs

I just want to display the version value of my package.json file within the footer of my app, but have no idea how to do that. I've read you could access those properties with process env object. Is it correct?

If you're running your app within NodeJs, you can access it by doing
process.env.npm_package_version
With ES6, you can also do
import {version} from './package.json';

The correct answers will be here in example:
Answer (this code include package.json file and get version)
const { version } = require('./package.json');
Answer
const version = process.env.npm_package_version
Please don't use JSON.parse, fs.readFile, fs.readFileSync and don't use another npm modules it's not necessary for this question.

Related

environment variable undefined in react js

I am trying to get the environment variable from .env file, I have followed all steps
but don't know why it's showing an undefined value
.env file
REACT_APP_NAME=user
in React
console.log(process.env.REACT_APP_NAME);
Ensure that the donenv package is installed (npm install dotenv)
Ensure the .env file is in the root directory
Make sure the following code is present in your main file:
import dotenv from "dotenv";
dotenv.config();
The import statement in the above code may need to be adjusted based on what stack you're using. I'm assuming this is node, since you haven't provided any details. Comment and let me know if this doesn't work.

Can't create npm package with nested react hooks via webpack

I'm trying to create npm package with some react hooks for my webrtc project. But found some mistakes
Current research process accumulated in github repo with reproducible example
According to project structure, problem looks like:
packages
sdk
store/call <-- contains useCall and withCall. Call useDevices inside useCall
store/devices <-- contains useDevices and withDevices
webpack.config.js
entry -> store/call
entry -> store/devices
ui
dynamic-component
useDevices <-- return store
useCall <-- return store
useDevices <-- return undefined. PROBLEM HERE
What already try:
use dependOn - after this, ui failed with import bundle. Explained in webpack issue, but not result
move store/devices into separate subproject with webpack.config.js and import it in sdk. Add it into webpack "externals" in sdk. But nothing changed :(
Can anyone advice how to debug this or configure for valid results?

Cant resolve ipfs-car/blockstore/memory when importing nft.storage

Im trying to store my nft metadata to ipfs using nft.storage (Reactjs)
When I import the library as explained in their docs I get this error
enter image description here
I read a similar error online for web3storage library and that it is probably a webpack version issue, but there is no solution. Any ideas?
This is how I am importing it:
import { NFTStorage, File } from 'nft.storage'
Exactly as shown in the docs.
Since there's insufficient info on how to deal with this out of the box, this is how I resolved it. It worked fine.
Go to node_modules/nft.storage directory.
Make sure you have ipfs-car/dist/esm/blockstore and ipfs-car/dist/esm/pack. If not, install ipfs-car with npm i ipfs-car. Copy ipfs-car/dist/esm to nft.storage/src.
Inside nft.storage/src, update the ipfs-car import statements in the following files like so:
Inside platform.web.js, update to this: import { MemoryBlockStore } from 'ipfs-car/dist/esm/blockstore/memory'
Inside lib.js, update to this: import { pack } from 'ipfs-car/dist/esm/pack'
Inside token.js, update to this: import { pack } from 'ipfs-car/dist/esm/pack'
This solved my problem.
Crude but works.
importing pack from built version should also work but crude as well...the package doesn't work at all without doing these, they should update it...I will send a pull request later on.
import { Web3Storage } from 'web3.storage/dist/bundle.esm.min.js'
I just upgraded Create React App to 5.0.0 (which upgrades to webpack 5) and it's working fine. Some relevant tips here.

import/export according to environment variable

For a clientSide app I would like to select a specific import according to the environment variables that were setup in the package.json.
eg:`
if (process.env.IS_DEV)
import { store } from '../../../index.js
else
import { store } from './index.js';
`
Is there anyway to do this.
I currently receive the error -
Parsing error: 'import' and 'export' may only appear at the top level
As the error says, import can be only at top level.
If you are using some bundler such as webpack or parcel, you can use a require instead.
Pay attention: that both of the implementations will be inside the bundle, and only one of them will be executed.
You can use web pack dynamic import to enable this if you are using web pack 1
$ npm install babel-plugin-dynamic-import-webpack --save-dev
then in .babelrc
{
"plugins": ["dynamic-import-webpack"]
}
https://github.com/airbnb/babel-plugin-dynamic-import-webpack
in the newer versions of web pack, you can do this without Babel
https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import
the other solution which mentioned before is using require
but i think here you can do it in a different way to avoid having this files in the bundled result you can add build script to run before building the dist which replace this import inside the file completely before bundle it to frontend app
Maybe is better to check process.env.IS_DEV inside the store file and export different values based on the current env

react evironment variables .env return undefined

I am building a react app and i need to fetch data from my api, now i want to store the api url as an environment variable. I have my .env file, i have dotenv installed, here is my code process.env.API_URL is returning undefined.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Home from '../src/components/Home'
import dotenv from 'dotenv'
import path from 'path'
class App extends Component {
render() {
console.log(process.env.API_URL)
return (
<div>
<Home/>
</div>
);
}
}
export default App;
Three things to note here
the variable should be prefixed with REACT_APP_
eg: REACT_APP_WEBSITE_NAME=hello
You need to restart the server to reflect the changes.
Make sure you have the .env file in your root folder(same place where you have your package.json) and NOT in your src folder.
After that you can access the variable like this process.env.REACT_APP_SOME_VARIABLE
Additional tips
No need to wrap your variable value in single or double quotes.
Do not put semicolon ; or comma , at the end of each line.
Read more here(my own post) and the official docs
You will probably need to call dotenv.config() as suggested by the document
If you are using create-react-app, you don't need dotenv package. You will need to add REACT_APP_ prefix to the variable name in .env file. See the document here
when calling a .env variable from a JS file
you need to call it by process.env. prefix before you write the .env variable
thus it would look like process.env.REACT_APP_NOT_SECRET_CODE
and do not forget to start your variable name by REACT_APP_ prefix as mentioned in previous answers, otherwise react will ignore it for security reasons.
Add prefix REACT_APP_ on React environment variables.
apiKey: process.env.REACT_APP_API_KEY
Make sure .env file is in the root directory.
src/
.env
.gitignore
package.json
package-lock.json
Restart the development server after making changes in .env file.
Copy only the value inside the quotation marks and don't forget to remove trailing commas(It haunted me for several hours). These examples will give you an error.
REACT_APP_API_KEY=Ach2o1invVocSn25FcQhash209,
REACT_APP_API_KEY="Ach2o1invVocSn25FcQhash209",
REACT_APP_API_KEY="Ach2o1invVocSn25FcQhash209"
Make sure you used the prefix REACT_APP on every variable
Confirm that the variable names on the .env file match the ones on
your js file.For example,REACT_APP_KEY in .env versus
process.env.REACT_APP_KY
If the development server was running, stop it then rerun using npm
start it. I really struggled with this (variable is an undefined error).
Every time you update the .env file, you need to stop the server and
rerun it, as the environment variables are only updated during build
(variable is an undefined error).
Remove quotations from the values of the variables.
// Wrong:
REACT_APP_KEY=”AHEHEHR”
// Right:
REACT_APP_KEY=AHEHEHR
restart the vscode (close the project, close the editor)
open it again
launch the project
In my case it help a lot. Also remember to start the name of your key with REACT_APP_YOUR_NAME_KEY
If the above solutions don't work for you then please check where is your ".env" file place.
Like in my case everything I had done correctly but the mistake is I had placed the ".env" outside my project directory due to which I'm getting error.
Note: Your ".env" file should be in the same directory in which your "package.json" is.
Hey thanks guy what i did and worked was create a config.js file
const dev={
API_URL:"http://localhost:300"
}
const prod={
API_URL:"llll"
}
const config=process.env.NODE_ENV=='development'?dev:prod
export default config
Then i import wherever maybe in a component and get my data.
Another possible trap in which I fell was to define the variables not under the create-react-app folder but one above(where the Node server/backend .env is located). Make sure you don't do that because you will waste precious time, as I did today.
Solution:
1.Remove double quotation.("...").
2.Prefix Must be REACT_APP on every variable.
Right way:
REACT_APP_API_URL=http://localhost:8002
I hope its work.
In my case I started with naming the file process.env. As it happen and as the doc clearly states, the file should simply be named .env
try by clearing the cache also.
npx react-native start --reset-cache
FIX:
in babel.config.js, if you're using the optional configuration:
{
"plugins": [
["module:react-native-dotenv", {
"moduleName": "#env",
"path": ".env",
"blacklist": null,
"whitelist": null,
"safe": false,
"allowUndefined": true
}]
]
}
you should then import:
import {API_URL, API_TOKEN} from "#env"
instead of:
import {API_URL, API_TOKEN} from "react-native-dotenv"
the NPM Package description itself has this inconsistency
DO NOT STORE OR USE API KEYS IN FRONTEND CODE SINCE IT IS EASILY READABLE THROUGH DEV TOOLS
Saving API keys in .env and using them in your React app will still be unsecured since the API key can be read from DevTools.
Use some simple backend code that will act as a proxy to your service.
Send required data through a request and then the backend should use that data including the API key stored on the backend, and then make a request to some particular service that needs that API key.
No need to prefix it with REACT_APP_, just identify your environment -
if you are on development environment (npm start), you should be adding an environment variable in .env.development like - API_URL=http://example.com
if you are on production environment, updating .env should work
Then use the same in your JS file as process.env.API_URL
Note: I've tested this on React JS v16.8
If you are using dev server on localhost know this that .env doesn't work here, you need to deploy website on "normal" server, it is a safety reason to not allow browser to see .env in staging
I investigated a couple of options on how to set environment-specific variables and ended up with this:
You can directly use the dotenv-webpack(npm install dotenv-webpack --save) available in webpack to have access to any environment variable.
You just have to declare the plugin in your webpack.config.js file:
const path = require('path')
const Dotenv = require('dotenv-webpack')
module.exports = {
/*...*/
plugins: [
new Dotenv()
]
}
Just create the .env file in your root directory and set the variables there,
REACT_APP_API_URL=https://localhost:8080/api
REACT_APP_LOG_PATH=/usr/share/
Then you call it in your js file in the following way:
process.env.REACT_APP_API_URL
process.env.REACT_APP_LOG_PATH
I just found that I used different names for the variables :)
Also make sure that when you enter process.env.REACT_APP_YOURVARIABLE, your IDE don't add at the top of your file:
import process from "process";
This was my problem, I received undefined until I removed the accidentally added import

Resources