Share code between two React web projects - javascript

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

Related

How can i access evironment variables in present NodeJS from ReactJS

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.

React + backend - project structure when sharing code

I really like the folder structure as can be seen here when dealing with a React frontend and a some backend with express:
root
├── backend
| ├── node_modules
| ├── public
| ├── src
│ │ └── Server.ts
| ├── package.json
| └── tsconfig.json
├── frontend (created using create-react-app)
| ├── node_modules
| ├── public
| ├── src
│ │ └── Index.js
| ├── package.json
| └── tsconfig.json
I think that having separate packages with individual node_modules is reasonable since the frontend and backend are basically completely different things, e. g. they need different node modules. Also, this modular approach is visually appealing to me and the repository looks tidy.
However, I encounter a problem with this structure when I need to share content between the frontend and the backend. I added a shared folder under the root-of-project which contains its own project with its own tsconfig.json, package.json and so on. This approach is a mix of the approaches here and here. For the backend, this works totally fine: having set up the tsconfig.json appropriately (using TypeScript Project References and aliased imports), I can reference the file root/shared/src/myFile.ts like this:
import { myFunction } from #shared/myFile;
I created the React frontend using create-react-app. It's ok for me that alias imports don't work, so I would have to use (inside the src folder in frontend):
import { myFunction } from '../../shared/src/myFile';
Sadly, these imports from outside the src directory are not supported by create-react-app and I don't want to use eject since I have no experience with webpack and don't want to maintain all the configuration files on my own (that's why I used create-react-app in the first place).
I know I can move the shared content to the frontend's src directory. But this would mean, I had to add the tags needed for using Project References in TypeScript, e. g. setting composite to true, in the frontend's tsconfig.json which seems odd to me and feels more like a hack. I'd like to have a separate npm project with my shared content.
Since create-react-app does not inherently support imports from outside the src directory, I thought that maybe I'm getting the big picture wrong. Isn't the folder structure I use right now a valid way of how to setup a React project with a backend? What mechanism does create-react-app provide to link files between the frontend and the backend? I could also think of having a root project with a src folder and inside of that the two folders backend and frontend. But this means, that we'd have one shared node_modules folder in root.
It's my first project with React and I'd love to get to know some best practicese for this kind of architectural problem. Some links to trustful resources where project structures for full-stack React development are explained would be really helpful. Thank you 😊
It's perfectly reasonable to want to share code between your front and back end. It's one of the reasons to code in javascript instead of Ruby or PHP.
You can accomplish exactly what you want by using yarn instead of npm and yarn workspaces: https://yarnpkg.com/lang/en/docs/workspaces/. At the top level you set up three modules/packages in your package.json (make sure you name the workspaces correctly in their respective package.json files):
"workspaces": {
"packages": [
"backend",
"frontend",
"shared"
]
},
Once you do, you can import shared code in your CRA app or your back end simply like this:
import { myFunction } from 'shared/src/myFile';
The drawback is that you can't import react components from the shared directory into frontend as long as you are using CRA. This won't affect you now since you only have one react app. Should you need to share react components among multiple projects, look into some on the suggestions above like bit.dev.
ADDENDUM!!! It's now possible to use CRA and yarn workspaces to share React code, if you replace CRA with CRACO. All you do is create another workspace with the shared react code. Then create a symbolic link in each module where you want to access it:
root
├── fontend-one
| ├── symbolic link to frontend-shared
├── frontend-two
| ├── symbolic link to frontend-shared
├── frontend-shared
Each of the CRA front end modules modules also requires a craco.config.js file where you tell web-pack not to follow symbolic links:
module.exports = {
// ...
webpack: {
configure: {
resolve: {
symlinks: false
}
}
}
};
You import from shared-frontend normally:
import { myFunction } from 'shared-frontend/src/myFile';
It's a pretty lo-fi solution but has proven robust for the year we've been using it.
Architecture is a tricky one, everyone has a different opinion and every option has pro and cons.
Personally I believe its best to separate the backend and frontend into sperate projects and keep them that way. Now as JavaScript/React/Node encourage component-based approaches a really nice way of sharing code between them is Bit.dev.
https://bit.dev
I am currently using it to share components and functions between three web apps and a few Node microservices.
A good structure for React app can be found here, this one works well and scales nicely:
https://hackernoon.com/fractal-a-react-app-structure-for-infinite-scale-4dab943092af
As for Express, there are so many ways to structure the project but personally recommend a folder for your Routes, a folder for your Controllers, this is where the logic for Routes live. Then go from there. Check this link out:
https://www.freecodecamp.org/news/how-to-write-a-production-ready-node-and-express-app-f214f0b17d8c/
Depending on what your building you may not even need a full backend you can check out the JAMStack here for more info:
https://jamstack.org
I would consider separating them though as the project scales it makes it much easier to manage. You can release your front end on something like Netlify and then use something like AWS or Azure to host your Node/Express server.
Having separate sub-projects for frontend and backend makes perfect sense due to vastly different dependencies. Mixing it up increases disk space consumption in production deployments and goes against security guidelines. Your folder structure is reasonable (except for public/ subfolders I'm unsure about, maybe I'm missing something).
The approach import { myFunction } from #shared/myFile; is fine. Just don't use CRA.
For a project with a single frontend and a single backend there is no need for a shared\ top-level folder because the frontend is the only source of 'UI truth' (e.g. the source of types and components related to UI) that is consumed by the frontend and the backend is the only source of 'API truth' consumed by both frontend and backend. With this arrangement only #backend/api_shared_stuff needs to be shared.
Some links to trustful resources where project structures for full-stack React development are explained would be really helpful. On the one hand, usually project authors have to explain plenty of other things and on the other hand keep the documentation (typically a README) reasonably concise. You may find that providing a justification/explanation why the subdirectory structure is this and not that was not the top priority.

avoiding deep nested module imports in an ES6 JavaScript web project

I am trying to tackle that I am currently have with my JavaScript project structure. I am writing ES6 syntax with webpack. My current directory structure looks like this
project-dir
|_ packages.json
|_ webpack.config.js
|_ html
| |_ ***
| |_ ***
|_ js
|_ app.js
|_ routes
|_ abc-component
| |_ components
| | |_ abc1.js
| | |_ abc2.js
| |_ index.js
|
|_ xyz-component
| |_ components
| | |_ xyz1.js
| | |_ xyz2.js
| |_ index.js
|_ reducers.js
This is simpler structure. But the problem is that the "reducers.js" and the "abc1.js/xyz1.js" need access to the same functionality. So, if that functionality lives in "reducers.js" then the "abc1.js/xyz1.js" would have to import it as "../../reducers.js". If that functionality lives split up in "abc1.js" and "xyz1.js" etc, then "reducers.js" will have to import each one of them as ".\abc-component\components\abc1.js" and ".\xyz-component\component\xyz1.js". The first way, it feels like i am reaching way up and the second way, it feels like i am reaching way up. The code is also constrained to the structure of the file layout. This directory structure could go deeper down and we will end up with very ugly imports.
So, it makes sense for me to pull out this functionality that is shared by reducers.js and "abc1/js/xyz1.js" into a different module. In doing that i thought about putting that in a another git repo, but this functionality is very project specific and didn't want the hassle of putting it in another repo.
I tried creating a "lib" folder under the "js" folder and put the common functionality it in that folder along with a packages.json file. That way, i thought i would just add it as a "dependencies" in the project's package.json file with the "file:\lib\common" value. This way, it will reference that module locally. But this landed me in a load of trouble. The problems i am encountering are 1) I couldn't write ES6 in this common module since webpack is not processing it 2) Everytime I change something in the common.js, i have to run "npm install" 3) npm seems to be caching an old version of the common module ever after i change it and run "npm install". Not sure where it comes from, i did clean the npm cache by running "npm cache clean" 4) Even when i just write old javascript in this common module and not ES6, webpack watch does not pick up on changes to this file and re-render the app.
I was wondering if i could get some thoughts on how best to go about solving this problem. Also, thoughts about how i tried and exceptionally failed in solving the problem with a local module would be very helpful.
One way to deal with this is to put your common code into a node module and just import it like you would any other library.
This would work similarly to the "lib" idea you suggested but without needing relative imports.

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..

Excluding references from Typescript compilation?

I have a bit of a strange (but in my view sensible) scenario.
I have a web site, mobile application and maybe going forward a web server all written in Javascript. I have a huge chunk of functionality which is shared between all these systems. This shared stuff would be models, repositories, business logic etc etc.
If we exclude the web server bit as that is a future idea, the web application has a directory structure like this:
app
|- assets
|- models
|- services
|- migrations
|- view-models
|- views
|- descriptors
Now each of these applications is broken down into 2 areas, the core and ui sections, the core is the re-usable stuff such as models, services, migrations and the ui stuff is ONLY used for that application which would comprise of view-models, descriptors (Incase you are wondering views are all html and assets are css, images etc).
Before I was adopting typescript I had a build script which would basically combine all the core files together and minify them. Then it would combine all the UI ones together and minify them. That way in the mobile application I can then just use the my-app.core.min.js and everyone is happy, I am reusing all the re-usable components from the main web application. However I do not need the ui stuff as the mobile UI is completely different to the main web ui, and the web service would not even have a UI going forward.
SO!
With that context explained lets jump back to the Typescript problem at hand. Currently the typescript files are compiled by tsc.exe (version 0.83) via a build script, which just wraps the interaction.
So in the new Typescript world the structure now has a references folder like so:
app
|- assets
|- models
|- services
|- migrations
|- view-models
|- views
|- descriptors
|- references <- NEW ONE!
This references folder is automatically populated by the build script with all local references, so it will trawl through the whole directory tree find all typescript files and build a huge reference file, which is a file full of the reference declarations for local typescript file, to find out more about what im on about look over this question:
Can you create Typescript packages? like c# dlls
So now when I run the build script the following steps happen:
Compiling for Core
Find all *.ts files within the models, services, migrations folders and subfolders
Add all the previous files into an array and also add in the reference files
run tsc.exe with a command like so tsc.exe --out <something>.core.js <previous_file_list>
Compiling for UI
Find all *.ts files within the view-models, descriptors folders and subfolders
Add all the previous files into an array and also add in the reference files
run tsc.exe with a command like so tsc.exe --out <something>.ui.js <previous_file_list>
Now I was expecting this to output 2 files my-app.core.js which ONLY contained the core files, and a my-app.ui.js which ONLY contained the ui files. However they both include everything...
Now after thinking about this, it must be due to the references, as they are both referencing all files, however thats just a compilation dependency in my eyes, not something that needs to be compiled WITH the outputted javascript. In c#/java you would not expect a referenced dll/jar to be compiled into your outputted dll/jar, its just a runtime dependency which is required.
I have tried having 2 separate reference files, one for core and one for ui, but as the ui will depend on core I get same problem, although at least this way the my-app.core.js is devoid of any ui related guff.
So is there a way to have references but NOT have them be outputted into the generated javascript files?
You can accomplish this by generating definition files for your TypeScript files:
tsc --declaration FileName.ts
In your build script do this for each TypeScript file and use the generated FileName.d.ts as the reference instead of FileName.ts
I had the following files:
-BusinessObjects
--Product.ts
--Customer.ts
--Order.ts
--BusinessObjects.d.ts
BusinessObjects.d.ts looks like this:
/// <reference path="Customer.d.ts" />
/// <reference path="Order.d.ts" />
/// <reference path="Product.d.ts" />
with Product, Customer, and Order each have a reference to BusinessObjects.d.ts
when I run:
tsc --out combine.js Customer.ts Order.ts
The output only references Customer and Order, Product is not included. When I referenced the *.ts files directly in my BusinessObjects.d.ts file however the combined output did include the unwanted file.

Categories

Resources