Installing Babel to use with React and JSX - javascript

I'm new to React and Babel and JSX. I'm trying to figure out how to install Babel so it will "do the right thing" with React and JSX in the browser.
However, the documentation for Babel assumes that I already know the entire NPM/Node + many other package managers + frameworks ecosystem, which I don't.
Is there any documentation out there for someone who simply wants to use Babel to compile JSX for a React application? I want to learn how to do it on my machine (not on a hosted site) but it just seems like there is zero beginner documentation out there.
It also seems like various versions of these pieces no longer work together so I'm a bit confused about what I need.
So far I have downloaded React 16.2, and used npm to install Babel with
npm install --save-dev babel-plugin-transform-react-jsx
and have a node_modules/ folder in my folder where Babel is (seems to be version 6.24.1, no idea if that's the right one for React 16.2), and where I'd like to put my HTML and JavaScript.
But now I'm stuck. I have no idea how to get Babel to do what I need. I'd like to just write some HTML with some React + JSX in it and have the "right thing" happen, but cannot find any documentation as to how to do that.
Thank you!

You should start your project with Create React App (CRA).
It's a React app initializer made by the React team. It makes all the setup for you (including Babel and Webpack configurations) and add some really nice features to your development environment.
If you don't want to use CRA, you will need to install:
babel-core
babel-preset-env
babel-preset-react
Then create a file .babelrc in the root of your project containing:
{ "presets": ["env", "react"] }
Then install and configure Webpack to run the Babel transforms.
(Or you could also run Babel manually with babel-cli).
The React documentation slightly addresses the Babel setup problem here.
They also suggest to use CRA here.

Ah, I found an answer in a Beginner's Guide to React at https://egghead.io/courses/the-beginner-s-guide-to-reactjs.
Apparently there is a standalone Babel compiler you can just link to in the head of the document, along with the links to ReactJS and it "does the right thing". Yay! Here are the links I'm using:
<script src="https://unpkg.com/react#16.2.0/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom#16.2.0/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/babel-standalone#6.26.0/babel.min.js"></script>
In the script tag that contains the ReactJS and JSX code, you must use type=text/babel:
<script type="text/babel">...</script>
I hope this helps other people starting out with React and JSX.
I'm guessing I'll eventually need to learn how to use NPM, NPX, Node, Webpack, and Babel (and possibly other tools) to run production ReactJS code, but for now I'm hoping this will allow me to learn ReactJS without having to worry about all that.

As pointed out in the React website (about using a script to add JSX functionality):
This approach is fine for learning and creating simple demos. However, it makes your website slow and isn’t suitable for production.
So it suggests instead to use a JSX preprocessor named Babel (it works more or less like a CSS preprocessor would work, so translates JSX into javascript).
The only requirement is to have Node.js installed, so that you could download Babel and add it to your project as a npm.
Below the link to follow all the instructions:
Add react to website

This is not an exact answer to your exact question, but it may help some people who end up here. Forget Babel, skip the extra compilation step and the project bloat, and:
Use something like React.createElement():
React.createElement('div', {className="container"},
[
React.createElement('h1', {key: "title"}, 'Greetings'),
React.createElement('p', {key: "para"}, 'To the newcomer, ' + this.props.name + '!')
]
);
Or use preact:
h(
'div',
{ id: 'foo' },
h('span', null, 'Hello!')
);
In either case, nest elements to any depth desired.

Related

Do devDependencies affect bundle size?

I looked hard, and couldn't find a straight answer to this question.
Do the packages I add as devDependencies actually end up in the production bundle JS file and thus affect its size? Or is it only the dependencies that go into the bundle?
No it will not affect your bundle size because those package are only using in development mode. Let's take an example package like typescript
devDependencies: {
"typescript": "~3.2.5"
}
So I only need to have typescript compier, linting just in dev mode. And I'm not actually import typescript in my project because it's only use for dev mode. So if you are using webpack and you wont import typescript anywhere then in your project webpack will you tree shaking to eliminate code that don't need for production build so the bundle will not affect.
The answer is not that easy as might look. Here is clarification: https://github.com/webpack/webpack/issues/520#issuecomment-174011824
And adding relevant snippet here:
A browser app built by webpack has no runtime node dependencies, and thus all frontend dependencies should be listed as devDependencies. The dependencies vs devDependencies naming convention stems historically from node being a server side package manager, which was abused into a frontend package manager, and this is why the fields have names that are counter-intutive when applied to frontend dev, and is why every project ever is getting this wrong. It is as far as I can tell harmless to list frontend dependencies under dependencies, but it is wrong.
I hope this answers your question.

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.

Converting React component to a single js file to integrate it with a blank html

A react component is developed using JSX. How to convert it to browser understandable JS code and minified to 1 js file so that it can be included as a single script tag in html ?Am very new to Js world and heard of babel and webpack.not sure how to use it and covert it to the same.
I got things generated after react-scripts build.but images are not serving if i deploy them in weblogic as static
For converting jsx into browser runnable js code, you would have to use babel. You can use babel-preset-react for this(via configuring .babelrc).
Babel Preset for React
Complete steps:
Run npm install babel babel-cli babel-preset-react
Define .babelrc at project root level, with following content
{
"presets": ["react"],
}
Run babel {jsxFile}.jsx --out {jsFile}.js
Am very new to Js world and heard of babel and webpack not sure how to use it
The statement above tells me that setting up npm build pipelines might best be avoided.
So assuming you have the component in jsx and you would like to use the javascript version, you will need to "convert" it. If it is a component that doesn't change quite a lot, you can take a look at the online babel.io repl (this is recommended by the official documentation site as well).
However, this approach can be tedious if your component changes frequently. I can highly recommend create-react-app for development. It is an opinionated toolkit which hides away webpack and babel configuration, but at the same time, their opinions are well documented and work for many general use cases.
Edit
From your comments, it seems you are already using react-scripts, then the most probably problem I see is that you perhaps forgot to specify the homepage property in your package.json (see relevant documentation) By default CRA assumes your static assets are hosted at server root, I assume you are not deploying your WAR in ROOT context, so you need to provide a static location.
I have a similar setup, where I need to package my site built with react inside a war file, I have the following setup:
in package.json
"homepage": "/<webapp_context>/build"
Then with gradle, I copy the build folder in its entirety to the WAR file (same level as WEB-INF).
This instructs react-scripts to put relative paths in all the static assets it publishes (such as CSS, js and images) and the imports then work.

NPM package for react components without babel

I've build an UI component using react/ES6 and I need to reuse it for several other projects.
So I thought it could be a nice little npm package.
Turns out the default for npm packages seems to be:
Put ES6 modules under /src
Have a separate /lib where the transpiled files live
On every release transpile those modules to ES5
From my point of view this is some (needless?) overhead. The projects that will use the package will be written using ES6 as well, so there is no need to transpile the dependency.
Is there any way to bundle ES6 modules in an npm package and skip the transpile process - and accept the fact that projects need to use ES6 in order to to add this dependency?
Edit to clarify
#D-reaper right, fair enough. My problem is the importing side. I've build a package that includes Project.jsx. When attempting to import it I get the following error message:
ERROR in ./node_modules/foo/Project.jsx
Module parse failed: /../node_modules/foo/Project.jsx Unexpected token (14:11)
You may need an appropriate loader to handle this file type.
So my guess is, that webpack/babel can't handle the import of ES6 modules correctly, since they expect npm packages to include ES5 - is that a correct assumption? Can I work around that?
I will use https://github.com/insin/nwb to put my react components into npm packages.
why don't you try Bit as to share your components. You can use bit's compilers or your owns if you have custom use case. You can read a little more https://codeburst.io/start-using-bit-to-build-react-apps-like-lego-7e14920f8de2

When it comes to using react with yeoman

There are a ton of packages out there that have this all bundled up but I dont like the way they set up the projects and such so I was reading the Reactjs docs on installing with npm and my confusion is:
After installing it using npm install react or adding react to
package.json
Do I add this to the "devDependencies": {} or ...
for the require statement to work, do I need to include requirejs?
Can I just do grunt serv to start everything and auto compile the jsx or do I need to do this? (it seems like that might be answered for me ..... but how can I get it to auto compile the jsx when I run grunt serv)
I ask these questions and state I don't like the existing yo ... commands for this because they don't play nicely with bacbone.js So I was going to set this up my self. if there are any repos out there for yeoman that do this for me please point me to them.
dependencies vs devDependencies: for npm package.json, devDependencies are mainly used for the tooling around working on the project itself: testing tool chain and project building modules, for example. Things you'd often see in there: Mocha, Grunt, etc. So mostly for repo contributors and alike. As a consumer of React, you'd put it in dependencies, which are for modules that your code actually needs in order to work.
require isn't for requirejs. The naming clash is unfortunate. require() is part of CommonJS. Node uses CommonJS. Browserify too. Here, it's assuming that you're using Browserify, or maybe doing server-side React with Node.
I'm not sure what you've set up to use with grunt serve. There's nothing magical that makes it work by default. You do need to do what the link said. The --watch option will look for changes to your files and auto compile the jsx to js.
Hope that helps!

Categories