Using environment variables in React application - javascript

Our JavaScript resource just quit, so I, knowing nothing about front-end development, need to get my UI stood up. I'm trying to use an environment variable in the javascript, and it seems like there are 100 different ways to do it.
All I know is this is a react/node app. I start it with npm run start. It needs an endpoint I've defined in my .bash_profile, XREFS_BACK_URL. I thought I could just use process.env.XREFS_BACK_URL, but apparently that has to be defined in some file? I don't know what file or where it should be located.
Sorry to be so clueless - this just landed in my lap and I have to get it up quickly!
Update:
I created a .env file in the root directory. It's one line:
REACT_APP_XREFS_BACK_URL=http://localhost:8080
In my code, I try to use it like so:
var endpoint = process.env.REACT_APP_XREFS_BACK_URL;
console.log("endpoint is " + endpoint);
But the console shows that endpoint is UNDEFINED.
My package.json is here:
{
"name": "bulletin-board",
"version": "0.0.1",
"private": true,
"devDependencies": {
"babel-jest": "^22.4.1",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"jest": "^22.4.2",
"react-scripts": "0.2.1",
"react-test-renderer": "^16.2.0",
"webpack": "^4.6.0"
},
"dependencies": {
"font-awesome": "^4.7.0",
"match-sorter": "^2.2.1",
"namor": "^1.0.1",
"npm": "^6.0.0",
"react": "^15.2.1",
"react-dom": "^15.2.1",
"react-draggable": "^2.2.0",
"react-table": "^6.8.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject",
"test": "jest"
},
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"moduleFileExtensions": [
"js",
"json",
"jsx"
],
"moduleNameMapper": {
"^.*[.](jpg|JPG|gif|GIF|png|PNG|less|LESS|css|CSS)$": "EmptyModule"
},
"preprocessorIgnorePatterns": [
"/node_modules/"
],
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react",
"<rootDir>/node_modules/react-dom",
"<rootDir>/node_modules/react-addons-test-utils",
"<rootDir>/EmptyModule.js"
]
},
"eslintConfig": {
"extends": "./node_modules/react-scripts/config/eslint.js"
}
}

Your app was made with create-react-app. Here are the docs for adding / referencing environment variables: https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-custom-environment-variables
Create a file in the root folder called .env with the contents:
REACT_APP_XREFS_BACK_URL=put_whatever_here
Then access this variable in your JavaScript via:
process.env.REACT_APP_XREFS_BACK_URL

Dont sure, if it actual for you, CNDyson, but I think it might be helpful for newers like me:
npm install --save dotenv
create .env file in the root directory
declare there REACT_APP_**VARIABLE_NAME** = dont forget about REACT_APP
use it like this: process.env.REACT_APP_**VARIABLE_NAME**
Highly recommend to explore these links:
https://create-react-app.dev/docs/adding-custom-environment-variables/ -official documentaion
https://www.npmjs.com/package/dotenv - dotenv

The problem is that usually you want to access the environments variables present on the server that host your application.
With the described solution you will never be able to do docker run --env FOO="value of foo" my-org/my-app
then access FOO in the app like process.env["FOO"].
create-react-app bundle the environment variables that are defined when you run yarn build.
If you want, for example, access the environment variables defined in the docker container check out: react-envs

At first create a file named env.local beside package.json
and try to secure environment variables REACT_APP_YOUR ENV FILE NAME
now set the secured name to your firebase file and push it
as simple as that

Related

React-Scripts and Jest - No tests found on running npm test

I am testing reducers and storage.
I read the jest tutorial-react manual and it's a little different from mine, but I also found information that "react-scripts test" should also work
package.json
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"dependencies": {
"#testing-library/jest-dom": "^5.16.1",
"#testing-library/react": "^12.1.2",
"#testing-library/user-event": "^13.5.0",
"classnames": "^2.3.1",
"faker": "^4.1.0",
"jest": "^27.4.7",
"miragejs": "^0.1.43",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.0",
"redux": "^4.1.2",
"seedrandom": "^3.0.5",
"web-vitals": "^2.1.3"
},
"devDependencies": {
"jest-watch-typeahead": "^0.6.5",
"prettier": "^2.5.1"
}
Commands
npm test
npm test --config jest.config.js
npm test --setupFile ./src/setupTests.js
npm test --setupFiles ./src/setupTests.js
Output
Active Filters: filename .\\src\\setupTests.js/
› Press c to clear filters.
Watch Usage
› Press a to run all tests.
› Press f to run only failed tests.
› Press o to only run tests related to changed files.
› Press q to quit watch mode.
› Press p to filter by a filename regex pattern.
› Press t to filter by a test name regex pattern.
› Press Enter to trigger a test run.
On pressing "a",
No tests found, exiting with code 0
Watch Usage: Press w to show more.
./jest.config.js
// Sync object
/** #type {import('#jest/types').Config.InitialOptions} */
const config = {
setupFiles: ['./src/setupTests.js'],
verbose: true,
};
module.exports = config;
./src/setupTests.js
import '#testing-library/jest-dom/extend-expect';
test('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3);
});
This is what the Jest documentation says about how it finds test files:
By default it looks for .js, .jsx, .ts and .tsx files inside of __tests__ folders, as well as any files with a suffix of .test or .spec (e.g. Component.test.js or Component.spec.js). It will also find files called test.js or spec.js.
Since the setupTests.js filename does not meet this criteria, Jest does not recognize it as a test file. If you rename the file to end with .test.js or move it into a __tests__ folder, Jest should be able to find it and run the test. If you need to keep the filename as is, this default behavior can be changed by setting testRegex in jest.config.js (read more about this setting here).
The setupFiles property in jest.config.js is used for setting up the environment before the tests actually run. The documentation for that setting can be found here, but it doesn't appear to be necessary to do any setup for this case based code you provided.

Babel-loader not transpiling JSX component. ModuleParseError

I'm trying to build a standalone component as a package. I'm using webpack to transpile all the CSS and JS/JSX files into JS. I'm able to build the package and pack it into a .tgz file using npm pack. However, when I install the package in another project and try using the component from the installed package. I'm getting this error:
ModuleParseError: Module parse failed: Unexpected token (34:8)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
And, in the terminal of the running project, I get this:
error - SyntaxError: Cannot use import statement outside a module
webpack.config.js
const path = require('path')
module.exports = {
mode:'production',
entry:'./src/components/StandaloneComponent.js',
output:{
path:path.join(__dirname,'dist'),
filename:'StandaloneComponent.js',
libraryTarget:"commonjs2"
},
module:{
rules:[
{
test:/\.js|jsx$/,
exclude:/(node_modules)/,
use:'babel-loader'
},
{
test:/\.css$/,
use:[
'style-loader',
'css-loader'
]
}
]
},
resolve:{
alias:{
'react':path.resolve(__dirname,'./node_modules/react'),
'react-dom':path.resolve(__dirname,'./node_modules/react-dom'),
'next':path.resolve(__dirname,'./node_modules/next')
}
},
externals:{
react:{
commonjs:"react",
commonjs2:"react",
amd:"React",
root:"React"
},
"react-dom":{
commonjs:"react-dom",
commonjs2:"react-dom",
amd:"ReactDOM",
root:"ReactDOM"
},
next:{
commonjs:"next",
commonjs2:"next",
amd:"Next",
root:"Next"
}
}
}
package.json
{
"name": "testcomponent",
"version": "1.0.3",
"description": "A lightweight and easy to use package.",
"main": "./src/components/StandaloneComponent.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [
"NextJS",
"react"
],
"peerDependencies": {
"next": "^12.0.7",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"prop-types": "^15.7.2"
},
"devDependencies": {
"#babel/core": "^7.16.0",
"#babel/preset-env": "^7.16.4",
"#babel/preset-react": "^7.16.0",
"#babel/preset-stage-0": "^7.8.3",
"babel-loader": "^8.2.3",
"css-loader": "^6.5.1",
"next": "^12.0.7",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"style-loader": "^3.3.1",
"webpack": "^5.64.4",
"webpack-cli": "^4.9.1"
}
}
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
I further installed this package in another project like this:
npm install path/to/tgz/testcomponent-1.0.3.tgz
And then imported the component as:
import StandaloneComponent from 'testcomponent'
As a possible workaround, I tried changing the extension of the component file from .js to .jsx and rebuilt the .tgz, but got the same result.
Looking at the error, I feel that babel-loader is unable to convert JSX into JS, which further is causing the import error, but I'm not entirely sure about it.
What could be causing this error?
Any help is appreciated.
Thanks.
The regex rule that you are using to load the JS and JSX file i.e. test:/\.js|jsx$/ seems incorrect in this case. You can fix it in following two ways:
Using capture groups: So when using or you need to capture the both the character sets as /\.(js|jsx)$/. This will consider both js and jsx extension. The earlier version just doesnt match the regex properly because of missing character set.
Using ? occurrence: You can also modify your regex to use the x as an zero or one occurrence using ? matcher. So the other option will be /\.jsx?$/
I believe you need to include the package you installed under include otherwise it looks like Webpack is configured to ignore your node_modules folder:
exclude: /(node_modules)/,
So make sure to let Webpack know what folders in node_modules that you do want to compile
include: [
path.resolve(__dirname, 'node_modules/testcomponent'
]

Node modules won't import in my Vue.js project

I'm trying to import a node module installed through NPM inside a Vue.js single file component. Every time, whatever the module is, it won't work and throw an error such as These depedencies were not found. I'm following the install instructions right (at least I think) but I guess I'm missing something.
Example :
Trying to install the swiper.js module.
I did the NPM install in the right folder, then in the component where I want to use it I added the following lines such as explained on their website :
import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/css';
And when I'm starting my server I get this error :
These dependencies were not found:
* swiper/css in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/ProductCarousel.vue?vue&type=script&lang=js&
* swiper/vue in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/ProductCarousel.vue?vue&type=script&lang=js&
To install them, you can run: npm install --save swiper/css swiper/vue
Edit :
Here is my package.json file :
{
"name": "x",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"bootstrap": "^5.1.1",
"bootstrap-vue": "^2.21.2",
"core-js": "^3.6.5",
"swiper": "^7.0.5",
"vue": "^2.6.14"
},
"devDependencies": {
"#fortawesome/fontawesome-free": "^5.15.4",
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^6.2.2",
"vue-template-compiler": "^2.6.11",
"webpack": "^4.46.0"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
Everything looks okay, apart from import 'swiper/css'; not needing to be imported.
You could try to delete your node_modules folder and running npm install again
In vue to make js script available you should import it in every component you would like to use in .
Or you can make it available globally by importing it in in main.js
For style you should import it in app.vue after opening style tag to make it global for every component style.
If we can take bootstrap as example.
In main.js
import 'bootstrap'
In app.vue
<style lang="scss"> #import './node_modules/bootstrap/scss/bootstrap';</style>

Jest and Create-react-app: Cannot use import statement outside a module

I have a React Native application where I have some files with some methods that calls certain endpoints. When I try to run Jest is throwing me an error at a local file that is imported.
I have the next package.json:
{
"name": "appName",
"version": "1.0.0",
"description": "some description",
"main": "index.js",
"scripts": {
"test": "jest"
},
"author": "",
"license": "ISC",
"dependencies": {},
"devDependencies": {
"#babel/core": "^7.14.2",
"#react-native-community/async-storage": "^1.12.1",
"#react-native-community/netinfo": "^6.0.0",
"isomorphic-fetch": "^3.0.0",
"jest": "^26.6.3",
"jest-fetch-mock": "^3.0.3"
},
"jest": {
"automock": false,
"setupFiles": [
"./jest.setup.js"
]
}
}
And the jest.setup.js file is the following:
import mockRNCNetInfo from '#react-native-community/netinfo/jest/netinfo-mock.js'
jest.mock('#react-native-community/netinfo', () => mockRNCNetInfo)
For the moment, this content is commented, otherwise will throw the same error like in the picture.
I tried to test the same stuff in another project where this #react-native-community/netinfo package wasn't saved in devDependencies but in dependencies and it worked but I am not sure if this is the problem. In this specific project I can't let this package as a dependency, it should be in devDependencies.
I found a lot of issues on this but none of them worked on this case, I don't know what to do anymore. Thank you for your time!
I got this error when I was creating tests with Create-react-app Typescript Jest Axios. Perhaps the following entry in package.json might help.
"jest": {
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
},
{ "transformIgnorePatterns": [
"node_modules/(?!#shotgunjed)/"
]
},
I found this answer on internet and it worked for me with some small add-ons but I will post it here maybe will help someone in future:
install babel-jest, babel-preset-env, #babel/runtime and react (the last one might be possible to be necessary only if some other package requires it)
create .babelrc file in root directory and add:
{
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
Run your code and should be good to go

Trouble importing custom library from a repository into an Ember project as a dependency

I am developing a WebGL library that I would like to import into an EmberJS project as a dependency. Unless I'm mistaken, I believe that I can do this via the repository directly without having to make an npm package but I am having trouble getting it to work.
I have made a watered down library and ember project in a couple repos here and here respectively to demonstrate my problem.
If you clone the library and run npm run build it'll make a test bundle which can be called by the test html file packageTest.html. It should print out 'Hello World Test Member is: 5'.
In the Ember project I have a component in which I would like to import the 'HelloWorld' class from the library and call one of its member methods.
import Ember from 'ember';
//import HelloWorld from 'npm-package-test';
export default Ember.Component.extend({
isWide: false,
actions: {
toggleImageSize() {
// var h = new HelloWorld();
// console.log(h.print());
this.toggleProperty('isWide');
}
}
});
When I uncomment the import statement I get the console error
Error: Could not find module 'npm-package-test'
I'm still pretty new to npm packaging and how dependencies work (and know next to nothing about Ember) but from my limited understanding I feel like this method should work the way I currently have it.
For the library, I have the source files being babeled into ES5 in its lib folder. As you can see in the package.json for the library below I have the main set to the index file in the lib folder so that the Ember project can pull the babeled modules.
Library: package.json
{
"name": "npm-package-test",
"version": "1.0.0",
"description": "JibJab Render Library for eCards",
"main": "lib/index.js",
"scripts": {
"prepublishOnly": "npm run build",
"build-test": "browserify test.js > demo/testbundle.js",
"build": "babel ./src -d ./lib && npm run build-test",
"lint": "eslint ./src",
"test": "nyc mocha --require babel-core/register"
},
"repository": {
"type": "git",
"url": "git+https://github.com/nhoughto5/NPM_PackageTest.git"
},
"author": "JibJab",
"license": "ISC",
"bugs": {
"url": "https://github.com/nhoughto5/NPM_PackageTest/issues"
},
"homepage": "https://github.com/nhoughto5/NPM_PackageTeste#readme",
"devDependencies": {
"babel-cli": "6.26.0",
"babel-preset-env": "1.6.1",
"eslint": "4.19.0",
"mocha": "5.0.4",
"nyc": "11.6.0"
},
"nyc": {
"reporter": [
"lcov",
"text"
]
},
"dependencies": {
"domready": "^1.0.8"
}
}
For reference, here is the lib/index.js which should be the entry point of my library:
Library: lib/index.js
'use strict';
module.exports = {
TestClass: require('./TestClass'),
HelloWorld: require('./HelloWorld')
};
In the ember project I have the library repository listed as a dependency:
Ember: package.json
{
"name": "test-ember-app",
"version": "0.0.0",
"description": "Small description for test-ember-app goes here",
"license": "MIT",
"author": "",
"directories": {
"doc": "doc",
"test": "tests"
},
"repository": "",
"scripts": {
"build": "ember build",
"start": "ember server",
"test": "ember test"
},
"devDependencies": {
"broccoli-asset-rev": "^2.4.5",
"ember-ajax": "^3.0.0",
"ember-browserify": "1.2.1",
"ember-cli": "2.13.1",
"ember-cli-app-version": "^3.0.0",
"ember-cli-babel": "^6.0.0",
"ember-cli-dependency-checker": "^1.3.0",
"ember-cli-eslint": "^3.0.0",
"ember-cli-htmlbars": "^1.1.1",
"ember-cli-htmlbars-inline-precompile": "^0.4.0",
"ember-cli-inject-live-reload": "^1.4.1",
"ember-cli-mirage": "0.4.3",
"ember-cli-qunit": "^4.0.0",
"ember-cli-shims": "^1.1.0",
"ember-cli-sri": "^2.1.0",
"ember-cli-tutorial-style": "2.0.0",
"ember-cli-uglify": "^1.2.0",
"ember-data": "^2.13.0",
"ember-export-application-global": "^2.0.0",
"ember-load-initializers": "^1.0.0",
"ember-resolver": "^4.0.0",
"ember-source": "~2.13.0",
"ember-welcome-page": "^3.0.0",
"loader.js": "^4.2.3"
},
"engines": {
"node": ">= 4"
},
"private": true,
"dependencies": {
"npm-package-test": "git+https://github.com/nhoughto5/NPM_PackageTest.git"
}
}
When I run npm install in the ember project I can see that the folder structure from the library appears in the node_modules folder. To my limited experience, everything seems correct but for some reason I am still getting this undefined module error.
Is there a step I've missed or some crucial detail I'm missing?
Yes, there’s one step you are still missing. For Ember-CLI to understand that you want to include your npm package in your app’s vendor files, you’ll need to use app.import as outlined here: https://guides.emberjs.com/v3.0.0/addons-and-dependencies/managing-dependencies/
That approach with app.import has existed since Ember-CLI 2.15, but if you are on an older version you’ll need to upgrade first.

Categories