How can i access evironment variables in present NodeJS from ReactJS - javascript

I want to use my .env variable presend in my nodejs root folder in reactjs. I tried using process.env.TEST but i always get undefined. any solutions?
My folder structure.
Project root
|-client
| |- //react project files
| |-app.js
|
|- //nodejs project files
|-.env
|-server.js
I want to access my .env variables in app.js and its components

You can use find-up to get your variables in your whole monorepo.
Find here a bright article on the usage.

Related

ServiceWorker in React and Typescript

When creating javascript-based React projects, installing a Service Worker is just a matter of changing serviceWorker.unregister() to serviceWorker.register() on index.jsx.
With such project structure:
- src
|- index.jsx
|- serviceWorker.js
When this code gets built, the /build folder will look as followed:
- build
|- static
| |- css
| |- js
| |- media
|
|- index.html
|- service-worker.js
This will work fine and will result in the Service Worker being registered properly.
On the other hand, when setting up a project in Typescript, given the same project structure (where the js / jsx files are ts / tsx instead), the /build will look something similar:
- build
|- static
| |- js
| |- bundled-js.chunk.js
| |- bundled-js2.chunk.js
| |- ..
|
|- index.html
So it seems Typescript builds the serviceWorker bundling it with all the other js files.
This will then result in the Service Worker not being registered, with the following error in console:
Error during service worker registration: DOMException: Failed to register a ServiceWorker for scope ('https://example.com/') with script ('https://example.com/service-worker.js'): The script has an unsupported MIME type ('text/html').
The live site with the error can be seen here; The open source code can be found here.
Any idea of what I may be doing wrong?
Any tip is greatly appreciated, thank you in advance!
Ok, looking at your code your using Create React App,. This uses webpack, and it's that what is bundling, it's nothing to do with Typescript, the same would happen for Javascript when it gets bundled.
The problem is overriding the webpack config's is not easy, there is CRACO -> https://github.com/gsoft-inc/craco/blob/master/packages/craco/README.md#webpack-api
But even then it's a little tricky!! You need to tell webpack not to bundle service-worker.js, Also I would take the register bit out of the server-worker, as that can be bundled and wants to be included in your bundle.
The simplest option might be just to compile the webworker separately with Typescript directly. And again, keep the register bit separate inside your normal build.

Share code between two React web projects

I have two different and separated web apps, both developed with React.
The two apps should share some React components.
I would like to have a general project structure as follow:
.
├── cms-client
├── my-app
└── shared
where:
cms-client and my-app are two standard React apps;
shared is a folder containing the shared components, that should be used by the other two apps.
I tried to add a symbolic link inside the two src folders of the apps, like:
ln -s ../../shared/ .
executed inside the src folder of each app.
In this case, when I try to use a shared component, the compilation failed:
../shared/Example.js
SyntaxError: /my-long-project-path/React/shared/Example.js: Unexpected token (6:12)
4 | render() {
5 | return (
> 6 | <div>
| ^
7 | <p>I am an Example of Shared Component</p>
8 | </div>
9 | )
like it is compiled as a standard js file, and not a React jsx file.
So, I'm trying a different approach, using a custom configuration of the jsconfig.json file. Now, my idea is to inject somehow the shared folder, but it seems impossible.
I could write a Gulp script that watch the shared folder, and then copy the contents inside the shared folder of the two project, but this isn't an optimal solution and very error prone (from my IDE, I need to pay attention on which of the three shared folder I'm editing). Moreover, the standard react-scripts is already watching the src folder for any changes. So, if someone has a better solution, it will be great!!!
Can you do npm link on your shared ?
This will compile, package, and copy to some location on you machine
Then on both cms-client and my-app do npm link shared
It will create symlink in node_modules point to the locally shared

Cannot find module - relative paths

I wrote a very simple local module to manage a few lines of localized text.
It uses node's require to load the language files, but I'm having trouble with paths, most likely.
I'm getting the Cannot find module error.
File structure
.
+-- local_modules
| +-- lang
| | +-- package.json
| | +-- index.js
+-- locale
| +-- en.js
| +-- de.coffee
+-- init.js
+-- index.coffee
+-- package.json
Relevant module code
Should require the file if it is not already loaded.
join = require('path').join;
_config.path = './locale';
lang = 'en';
_locales = {};
if(!_locales[lang]){
_locales[lang] = require(join(_config.path, lang));
}
Every file in the locale directory is a typical Node.js module, for example en.js:
module.exports = {
test: 'Hello World!'
};
The local module exports a function(req, res, next){}, which is used as Express middleware and is supposed
to attach the required object with localized strings onto res.locals, however, I'm seeing Cannot find module 'locale/en' error.
I've tried to manually add the .js extensions (but that shouldn't be neccessary as far as I know).
I have also tried different variations on the path, such as locale or /locale.
The module is called in index.coffee.
App is launched using init.js, which contains the following:
require('coffee-script/register');
require('./index');
Maybe it's just that the module is a .js (and the module itself doesn't have CoffeeScript as a dependency) so it can not load a .coffee file? Although CoffeeScript should be registered globally, or am I wrong? Either way, it doesn't work with the .js file either, so I guess it has something to do with paths.
path.join() also normalizes the created path, which (probably) means the ./ part was always removed, and what remained was a relative path.
Instead, when path.resolve() is used, it creates an absolute path, which is what is needed in this case.

Using dotenv in a Node JS module

I am building a Node app that returns results for a search using a Google Custom Search Engine(CSE).
I am going to separate the part of the app that sends the request to Google and returns the results into a module.
I use dotenv already in the app to store MongoDB credentials and the app's URL.
I also want to use dotenv in the module to store the Google CSE ID and the API key for the CSE.
I want my module to work independently of the main app but also to use the main app's dotenv file when it's a module.
Currently my module structure looks like this:
module
|
+-- node_modules
| |
| \-- dotenv
| |
| \-- (dotenv module's files....)
|
+-- .env
|
\-- index.js
This works perfectly on its own. The .env file stores the required environment variables and I can access them in the index.js file by requiring the dotenv module.
When included in the main app the structure looks like this:
app
|
+-- node_modules
| |
| +-- dotenv
| | |
| | \-- (dotenv module's files....)
| |
| \-- my_google_search_module
| |
| +-- node_modules
| | |
| | +-- dotenv
| | |
| | \-- (dotenv module's files...)
| |
| \-- index.js
|
+-- .env
|
\-- index.js
This also works. I store all the environment variables in the main app's .env file and by requiring dotenv in the app's index.js I can access those variables. Plus, the "my_google_search_module" seems to be pulling its required variables from the .env file in the root of the app. There is no .env file in the module.
My question is am I doing this the right way?
I have researched this further and can confirm that the module's .env is pulling the required environment variables from the app's .env file.
I believe this section from the dotenv readme, though not exactly related, verifies that -
https://www.npmjs.com/package/dotenv#what-happens-to-environment-variables-that-were-already-set
We will never modify any environment variables that have already been
set. In particular, if there is a variable in your .env file which
collides with one that already exists in your environment, then that
variable will be skipped. This behavior allows you to override all
.env configurations with a machine-specific environment, although it
is not recommended.
Yes, you are doing in a right way. There must be a single .env file in a whole project. But there is a trick to include it in the different directory structure.
For example:
Your index.js file is in /app/src, your .env file is in /app. Your index.js file has this
dotenv.config({path: "../.env"});
You could also use dotenv.config({path: path.join(__dirname, "../.env")});
for node projects, i would suggest to use npm package dotenv. You can find details on how to use it. do not forget to include require('dotenv').config() at the start of your project file, say index.js.
Now you can use .env contents anywhere you need. For example i want my server port to be 4000 which i define in .env as PORT=4000. Now, to use .env variables anywhere, simply provide variable name in suffix such as process.env.PORT. That is it. Though i am late on this post, hope this could be of any help.

How to organize folders and files on Meteor project?

I'm trying to understand Meteor as I create a project and I find some things a little difficult to understand so far.
1- When they say I can create a server and a client folder, where exactly I am meant to do so? Sibling of .meteor ? And will everything be at client's or server's scope when the app starts or do I have to do something else? If I create a foo.js and a foo function inside it in client folder, can I just call foo() in Meteor.isClient and it will work?
2- I need to create an upload folder so people can upload their stuff (images). So where am I supposed to do this? Plus, how can I get the absolute path to my project and find this upload folder inside?
During my attempts I tried the following:
fs = Meteor.npmRequire('fs');
__ROOT_APP_PATH__ = fs.realpathSync('.');
But __ROOT_APP_PATH__ is .meteor\local\build\programs\server. Quite hidden right?!
3- I saw some people uploading and saving files on MongoDB directly. This is something we usually don't do with relational databases. We move the file to a known folder on a CDN or on our own disk and save the hash or name of that file so we can easily find it. Isn't it encouraged with Meteor + MongoDB? Why would I save the file itself on Mongo instead of moving it to a folder?
not any specific way to do but meteor recommend it doing this way
http://docs.meteor.com/#/basic/filestructure
FOLDER STRUCTURE:
both/ (OR lib/) -- common code for server and client
|- collections/ -- declare collections (e.g Employer = new Meteor.Collection("employer");)
|- router / -- router code(e.g Router.route(..))
client/ -- client side code
|- global/ -- all global variable for client
|- helpers/ -- global helper for client (for all templates)
|- plugins/ -- all the plugins code(if you use any)
|- stylesheets/ -- css / less files
|- templates/ -- all templates
|- home.html -- home template(html)
|- home.js -- home template(js)
public/ -- images/icons/fonts (meteor looking at this file)
server/ -- server code
|- methods/ -- server methods/API (e.g Meteor.methods({...}))
|- publish/ -- publish code from server
this is the basic folder structure for meteor project which i follow. For further reference or Documentation. For any question feel free ask in comments..

Categories

Resources