Split react code from the app - javascript

I've been moving from jQuery to React and need some help understanding how to make webpack to split my code from react itself.
I'm using react to build widgets. Each is it's own "app" and multiple of them may be embedded to a non react page. Because of that, I need react included in the page only once (like when using jQuery). I'm currently using create-react-app as it's very easy to start with.
Could you please point me into the right direction?

You could work with multiple entries (documentation) if you would like to work with webpack. This may look like the following:
entry: {
react: ["react", "react-dom"],
app: ['./index.js']
}
Be aware of the fact that you can't use your own webpack-config in the apps created by create-react-app unless you remove or replace the whole react-scripts part, since they handle all of the webpack staff internal.
If you want to use your components external (like different websites), you should create a package (npm or those alike) for each of those. A different option would be to add everyone of those components as an entry point in the webpack->entry object. But if you want to use them external, this seems to be a huge overhead when serving from different hosts.

Related

How to make Node and React app to share classes

I'm building a Node and React app, both using TypeScript. Its directories tree is as follows:
My question:
Since I'm using the same language for both stacks, and in the future the React Native will be added also using TypeScript, I wonder how I can create one group of classes to be used for all of them.
Why I want to do this:
DRY (Don't repeat yourself): My intention is to take full advantage of using the same programming language in all layers so there's no sense creating two equal classes.
What I have tried so far:
I created a third folder called "util" and put a generic class just to test both Node and React using it. Like this:
In Node.js I used the command below to import it:
import Person from "../../util/person.class";
And in React.js, I used the same logic to import it:
import Person from "../../util/person.class";
As I already expected, both deny using files that are outside their respective root folders:
I also searched in the internet about this and I found some "eject" command that, once used, there's no way back, whatever. I'd like to avoid such ways. Is there any approach where I could take in my favor?
I also want to mention that I created a tsconfig.json for backend using "tsc --init" and set the rootDir as "./src/" and outputDir as "./dist/".
Thanks.
You could set up a third project that has the shared functionality. Then you can publish the shared package to a npm repository. And then you can install the shared package in the frontend and backend project.
If you want to send the react from the sever then the front-end files should be under the back-end folder
/app root
/ back-end
/shared-front-end-classes
/front-end-desktop
/front-end-mobile
Though this is not the best solution
The best solution is to host the front-end on a different server and make the
back-end totally functional with APIs
For example :
I have a blog that I host the
Front-end:
Github pages "Support react via a small npm package"
Back-end:
Hosted on Heroku
DB:
I am using mongoAtlas "A cloud DB"
now you have 3 separate places to hold all of your code independent of each other
Now for your other problem, you want to use the same classes over the two front-ends
For me, I usually make a small repo with all the components/ pages that I want then import this in any project for future use
I am not sure if this follows the DRY concept but you will not write your code twice

difference between library , package , module in js

I have started to learn react and I am very confused with the concept of packages.
and why we can't just use a simple link as cdn and there is a module which i don't understand it and what's npm and why i have to use it with react
Not trying to give the definite answer here, but trying to explain the 3 terms as simple as I can:
A module is just a file containing lines of JavaScript code.
A library uses one or many modules to provide a set of features.
A package is a downloadable, versioned library. Think of someone putting it in a box and shipping it to you, so you can import it and use it in combination with your own code.
so I came with conclusion and hope you tell me if I get it right or not .
-Module : it is justba javascript file but it's different from normal script that it has its own scope so you have to use import or export to exchange information between modules.
-Library : it is a group of modules or scripts that it is responsible for the function you want .
-package : can be one or more libraries but it is also contain files that don't deal with the functionality but it's only role to make sure the libraries and functional file work properly .
like react package it is come with react library deals with the functionality and also has babel compiler to make browser read and understand react library.
It is very much possible to use a simple link such as a CDN. Many packages also have links available, such as material UI. However, it quickly becomes unmanageable to use CDN links when your project grows, and it can affect performance and load times of your site.
Npm stands for Node package manager. It handles packaging for Node, where it would not be suitable to use a simple link.
It turns out that it is possible to also use npm for web applications, by combining it with a bundler. The bundler (such as webpack) takes all of your modules (JavaScript files and npm packages) and bundles it together so that you get a single script which you can run in the browser.

How to find dead code in a large react project?

In order to refactor a client-side project, i'm looking for a safe way to find (and delete) unused code.
What tools do you use to find unused/dead code in large react projects? Our product has been in development for some years, and it is getting very hard to manually detect code that is no longer in use. We do however try to delete as much unused code as possible.
Suggestions for general strategies/techniques (other than specific tools) are also appreciated.
Thank you
Solution:
For node projects, run the following command in your project root:
npx unimported
If you're using flow type annotations, you need to add the --flow flag:
npx unimported --flow
Source & docs: https://github.com/smeijer/unimported
Outcome:
Background
Just like the other answers, I've tried a lot of different libraries but never had real success.
I needed to find entire files that aren't being used. Not just functions or variables. For that, I already have my linter.
I've tried deadfile, unrequired, trucker, but all without success.
After searching for over a year, there was one thing left to do. Write something myself.
unimported starts at your entry point, and follows all your import/require statements. All code files that exist in your source folder, that aren't imported, are being reported.
Note, at this moment it only scans for source files. Not for images or other assets. As those are often "imported" in other ways (through tags or via css).
Also, it will have false positives. For example; sometimes we write scripts that are meant to simplify our development process, such as build steps. Those aren't directly imported.
Also, sometimes we install peer dependencies and our code doesn't directly import those. Those will be reported.
But for me, unimported is already very useful. I've removed a dozen of files from my projects. So it's definitely worth a shot.
If you have any troubles with it, please let me know. Trough github issues, or contact me on twitter: https://twitter.com/meijer_s
Solution for Webpack: UnusedWebpackPlugin
I work on a big front-end React project (1100+ js files) and stumbled upon the same problem: how to find out which files are unused anymore?
I've tested the next tools so far:
findead
deadfile
unrequired
None of them really worked. One of the reason is that we use "not standard" imports. In additional to the regular relative paths in our imports we also use paths resolved by the webpack resolve feature which basically allows us to use neat import 'pages/something' rather than cumbersome import '../../../pages/something'.
UnusedWebpackPlugin
So here is the solution I've finally come across thanks to Liam O'Boyle (elyobo) #GitHub:
https://github.com/MatthieuLemoine/unused-webpack-plugin
It's a webpack plugin so it's gonna work only if your bundler is webpack.
I personaly find it good that you don't need to run it separately but instead it's built into your building process throwing warnings when something is not ok.
Our research topic: https://github.com/spencermountain/unrequired/issues/6
Libraries such as unrequired and deadcode only support legacy code.
In order to find the unused assets, to remove manually, you can use deadfile
library:https://m-izadmehr.github.io/deadfile/
Out of box support for ES5, ES6, React, Vue, ESM, CommonJs.
It supports import/require and even dynamic import.
It can simply find unused files, in any JS project.
Without any config, it supports ES6, React, JSX, and Vue files:
First of all, very good question, in large project coders usually try many lines of code test and at the end of result, hard to find the unused code.
There is two possible that must be work for you - i usually do whenever i need to remove and reduce the unused code into my project.
1st way WebStorm IDE:
If you're using the web-storm IDE for JS development or React JS / React Native or Vue js etc it's tell us and indicate us alote of mention with different color or red warning as unused code inside the editor
but it's not works in your particular scenario there is another way to remove the unused code .
2nd Way unrequired Library: (JSX is not supported)
The second way to remove the unused code inside the project is unrequired library you can visit here : unrequired github
another library called depcheck under NPM & github here
Just follow their appropriate method - how to use them you will fix this unused issue easily
Hopefully that helps you
I think the easiest solution for a create-react-app bootstrapped application is to use ESLint. Tried using various webpack plugins, but ran into out of memory issues with each plugin.
Use the no-unused-modules which is now a part of eslint-plugin-import.
After setting up eslint, installing eslint-plugin-import, add the following to the rules:
"rules: {
...otherRules,
"import/no-unused-modules": [1, {"unusedExports": true}]
}
My approach is an intensive use of ESlint and make it run both on IDE ad before every push.
It points out unused variables, methods, imports and so on.
Webpack (which has too nice plugins for dead code detection) take care about avoiding to bundle unimported code.
findead
With findead you can find all unused components in your project. Just install and run:
Install
npm i -g findead
Usage
findead /path/to/search
This question recalls me that react by default removes the deadcode from the src when you run the build command.
Notes:
you need to run build command only when you want to ship your app to production.

Correct way to author Vue components that rely on parent build tools

I imagine this problem would apply to other frameworks that have a bit of a plugin/component ecosystem about them that rely on specific build tools (React components with JSX, etc). Vue is just my use-case.
I have authored several Vue components in the form of single .vue files which are published to NPM. The package.json for these component does not list any dependencies, as they themselves are intended to function within a parent project that uses webpack, vue-loader, sass-loader, etc. This is an example of one such component.
I am unsure about the best way to declare that these components rely on the parent package having said build tools. I am not confident that devDependencies is the correct place for them as the component itself has no development step that relies on these. peerDependencies seems more suitable but again I am not confident this properly matches what I am trying to achieve.
Looking through many of the components on the awesome-vue repository I can't see any use of peerDependencies and the devDependencies seem relevant to the development of the particular components themselves.
What is the correct way to author these components? It's almost like I need something like "peerDevDependencies".
Most component are, unfortunately distributed already compiled.
In my opinion the best way to distribute a component is to write as main the raw .vue file of the component.
You shouldn’t specify to use any particular tool, developers that pick up your package should be free to use the tool they want, be it Browserify or Rollup (or Webpack). The raw .vue format allows them to compile the .vue component with whatever tool they want and using whatever Vue version they want (within a range of course).
Moreover what I like to do is give the users the possibility to use the component straight away, even inside a browser, with just Vue as a <script> dependency. For this you would have to compile it and, yes, specify Vue as a peerDependency in the sense that it’s needed in the page.
You can put meta information in the package.json to tell CDN to pick up the compiled version when inside the browser, this is very handy so the user just specify the name of the package without worrying about the file name or version.
Speaking only as a consumer of Vue.js components, I think specifying your build dependencies as peerDependencies is the best solution. You are using what is a pretty standard build pipeline, but I think that having them specified is important. These are not strictly devDependencies or dependencies depending on where they are going to be compiled by the end user.
I'd suggest you use "module" property on the package.json for the raw vue file, and the "main" as the compiled one. module is a property getting standardized and webpack and rollup already understand it.
For more info see setting up multiplatform npm packages article.

How can I structure/access the react components of my non node.js application?

I have a production application whose folder structure is much like you would expect:
/project
/css
/js
/php
/fonts
/images
/index.php
I have recently begun learning to use react.js and I would like to start developing new features using react while leaving all existing functionality as is and I understand that react.js can certainly be used this way.
What isn't entirely clear, is how to structure the files in my non node.js project and access them.
For example, I tried searching for this and found this article which proposes the following structure
and states:
Here index.jsx works as the entry point of the application. It uses ReactDOM.render to render App and gets the party started. App in turn does something interesting with Note. If I wanted yet another component, you would simply add it below /components.
Presumably this is a node.js project where index.jsx can call something like require('components/App.jsx');, but how do I achieve the same in my non node.js project.
Consider if I set the following folder structure:
/project
/css
/js
/php
/fonts
/images
/react
/components
/App.jsx
/Note.jsx
/scripts
/featureFoo.jsx
/index.php
Given the above, I'd like to have index.php load react/scripts/featureFoo.jsx which would somehow include/use react/components/App.jsx and react/components/Note.jsx
I figure I could have script tags in index.php to load all of the components then featureFoo.jsx but I feel like there is a more react way to do this.
So
How can I structure/access the react components of my non node.js application?
Im tagging node.js as I feel those users may well bring insight regarding this possibly from having to deal with multiple projects/aproaches.
In order to import/require other modules in a non-node.js (i.e. browser-based) JS application, you'll need to use a bundler such as webpack or browserify.
They work by starting at your "entry" file (index.jsx in your case) and recursively following all of your imports/requires. Then it smartly bundles everything up into a single "output" file, which includes everything your application uses, that you can link in your HTML.
You can also use more complex configurations with multiple entry and output files, or even dynamic loading of "chunks" at certain points in your application. But the above is the most basic use case, and works well for most simpler projects.
These bundlers have some other cool features as well. For instance, with webpack (with additional plugins and loaders) you can:
Write ES6/ES7 JavaScript that gets compiled (via babel) into cross-browser compatible ES5
minify/uglify your output JS
import/require non-js files such as CSS, images, and webfonts, and choose how to process these imports (e.g. pre/post-process your CSS, or optimize your images)
Extract all imported CSS into a single .css file
Use webpack-dev-server (or webpack-dev-middleware) to take advantage of hot module replacement, which makes developing JS apps easier by letting you see your changes take effect instantly in the browser without having to refresh or lose your app's state.
And a lot more. The world of bundlers is a pretty big ecosystem with a lot to learn, but it's totally worth getting into.
A good place to get started is the excellent Survive JS series of tutorials.
However, if you're still learning React, then diving into webpack and the entire ecosystem of JavaScript tooling can be overwhelming. It will probably be easier and a more efficient use of your time to keep things simple at first, and then only get into bundlers etc. after you get comfortable with React.

Categories