ReactJS - Babel usage problems to compile .jsx - javascript

For a quick test, i've created my main.jsx file written in ES6 for my ReacJS app:
main.jsx
import React from 'react'
import { render } from 'react-dom'
import { Router, Route, Link } from 'react-router'
class TestComponent extends React.Component {
render() {
return <div className="test">...</div>;
}
}
Then i compile my code with browserify and babel:
browserify -t babel main.jsx -o public/js/bundle.js
I get this error: Error: Cannot find module 'babel'
What's the cleanest way to compile ES6 code with ReactJS?

If you are using Browserify, you can use the transform 'babelify' to compile your ES6 code. Check it out here:
https://github.com/babel/babelify

Related

Redux Error: You are currently using minified code outside of NODE_ENV

the full error is:"You are currently using minified code outside of NODE_ENV === "production". This means that you are running a slower development build of redux. ..."
I already tried installing webpack and setting the mode to "production" in the webpack.config.js file but it didn't work. I have a running project with redux and react-redux installed. As soon as I add the import statement to the App.js:
import { createStore } from 'redux'
it throws the error. I use expo for my app and ideally I don't want to use webpack. According to the Redux documentation webpack is not necessary.
Why does it throw the error?
App.js
import * as React from "react";
import { AppFontLoader } from "./AppFontLoader";
import { Drawer } from "./Navigation";
//import { createStore } from 'redux' //uncommenting this line throws the error
export default class App extends React.Component {
render() {
return (
<AppFontLoader>
<Drawer />
</AppFontLoader>
);
}
}

npm build with Browserify - Error: Cannot find module

When running npm build with:
"build": "browserify -t [ babelify --presets [ es2015 react ] ] app/assets/app.jsx -o public/javascripts/app.js"
I am getting following error:
Error: Cannot find module 'components/maininput.jsx' from 'C:\Users\Work\Documents\NetBeansProjects\Project\app\assets'
Project structure looks like this:
app
|
└────assets
│ app.jsx
|
└───components
maininput.jsx
import in app.jsx looks like this:
import React from 'react';
import ReactDOM from 'react-dom';
import { MainInput } from '../components/maininput.jsx'
export in maininput.jsx looks like this:
export default class MainInput extends React.Component {
//some code and render()
}
I also created GulpFile and also there getting same error:
{ Error: Cannot find module '../components/maininput.jsx'
EDIT:
I have found out that it is working only if I provide full path to component, which is strange. Anyone knows what might cause this problem? Probably some enviroment variable or ?
Use ./ at the beginning of your import path:
import { MainInput } from './components/maininput.jsx'

Having issues with ES6 based multiple (React) Node.JS Module imports

I've been working on a React project and I'm having an issue trying to use ES6 to import several exported React node modules.
This is my code:
I should be able to include the AddFriendInput and FriendList from the hello folder without any issue. But I get this error when webpack/babel compiles:
ERROR in ./src/common/containers/Menu/indexRender.js
Module not found: Error: Cannot resolve 'file' or 'directory' ../../hello in /Users/markpaul/Documents/projects/patient-portal-app/src/common/containers/Menu
# ./src/common/containers/Menu/indexRender.js 122:13-35
The content of my AddFriendInput.js file is like so:
import React, { Component, PropTypes } from 'react';
export default class AddFriendInput extends Component {
constructor(props, context) {
super(props, context);
this.state = {
name: this.props.name || ''
};
}
render() {
return (
<div>
</div>
);
}
}
I use webpack with babel to transpile my files. My Babel config is:
{
"presets": ["react", "es2015", "stage-1"]
}
The only way I can get it to work is to do this:
import AddFriendInput from '../../hello/AddFriendInput/AddFriendInput';
import FriendList from '../../hello/FriendList/FriendList';
But as you can see, this looks horrible.
Can someone please help.
Thanks in advance.
Create home/index.js
import AddFriendInput from './AddFriendInput'
import FriendList from './FriedList'
export { AddFriendInput, FriendList }
OLD ANSWER:
Rename AddFriendInput.js to index.js and after that you can import like this:
import AddFriendInput from '../../hello/AddFriendInput'
ES6 module doesn't automatically load nested directories/files
import by directory name (../../hello) implies that you have hello/index.js
updates
you could just create home/index.js as #Sergey mentioned or there is a module named auto-import that watch your directory and update index.js for you.
I think you are not understand the commonJS.
if the ../../hello is a folder, nodejs will find index.js file. so you must be have a file ../../hello/index.js.
import AddFriendInput from '../../hello/AddFriendInput/AddFriendInput';
import FriendList from '../../hello/FriendList/FriendList';
module.exports = {
AddFriendInput,
FriendList
};

Create react app with browserify has error

I am learning React and try to create a simple React application.
I want to use ES2015 modules and some ES6 features so I installed Babel and browserify via npm.
These are node modules that I installed:
babel
babel-preset-es2015
babel-preset-react
babelify
browserify
gulp
reactify
vinyl-buffer
vinyl-source-stream
react
react-dom
I want to make script into several files (like itemComponent as React) and merge them into dist/app.js that actually website loads. For this, I used gulp!
This is my gulpfile.js:
var source = require('vinyl-source-stream');
var gulp = require('gulp');
var browserify = require('browserify');
var reactify = require('reactify');
var babelify = require('babelify');
gulp.task('default', function() {
return browserify('./source/' + file)
.transform(babelify, { presets: ["es2015", "react"] })
.bundle()
.pipe(source(file))
.pipe(gulp.dest('./dist'));
});
Gulp is actually working well, everything is transpiled good without error. But check the website, it says:
app.js:19474 Uncaught ReferenceError: React is not defined
So I removed react and react-dom installed via npm, and just download React and load from HTML simply just use script tag, and it works.
But I want to include react like this:
import React from 'react';
But it is not working. This is my app.js:
import React from 'react';
import ReactDOM from 'react-dom';
import ItemList from './components/itemlist';
let items = [ ... ];
class App extends React.Component {
render() {
return (
<div>
<h1>List of items:</h1>
<ItemList items={this.props.items} />
</div>
)
}
}
ReactDOM.render(<App items={items} />, document.getElementById('app'));
I don't know what is the problem and I don't want to load each react file using script tag. Is there something I missed?
Reason of this issue were I forgot to import React module in child components, .
JSX will transpile to something like React.createElement, but there wasn't React exists so that's why I have Reference Error.

Uncaught ReferenceError: React is not defined

I am trying to make ReactJS work with rails using this tutorial. I am getting this error:
Uncaught ReferenceError: React is not defined
But I can access the React object in browser console
I also added public/dist/turbo-react.min.js as described here and also added //= require components line in application.js as described in this answer to no luck. Additionally,
var React = require('react') gives the error:
Uncaught ReferenceError: require is not defined
Can anyone suggest me on how to resolve this?
[EDIT 1]
Source code for reference:
This is my comments.js.jsx file:
var Comment = React.createClass({
render: function () {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{this.props.comment}
</div>
);
}
});
var ready = function () {
React.renderComponent(
<Comment author="Richard" comment="This is a comment "/>,
document.getElementById('comments')
);
};
$(document).ready(ready);
And this is my index.html.erb:
<div id="comments"></div>
If you are using Babel and React 17, you might need to add "runtime": "automatic" to Babel config.
In .babelrc config file this would be:
{
"presets": [
"#babel/preset-env",
["#babel/preset-react", {"runtime": "automatic"}]
]
}
I got this error because I was using
import ReactDOM from 'react-dom'
without importing react, once I changed it to below:
import React from 'react';
import ReactDOM from 'react-dom';
The error was solved :)
I was able to reproduce this error when I was using webpack to build my javascript with the following chunk in my webpack.config.json:
externals: {
'react': 'React'
},
This above configuration tells webpack to not resolve require('react') by loading an npm module, but instead to expect a global variable (i.e. on the window object) called React. The solution is to either remove this piece of configuration (so React will be bundled with your javascript) or load the React framework externally before this file is executed (so that window.React exists).
If you are using Webpack, you can have it load React when needed without having to explicitly require it in your code.
Add to webpack.config.js:
plugins: [
new webpack.ProvidePlugin({
"React": "react",
}),
],
See http://webpack.github.io/docs/shimming-modules.html#plugin-provideplugin
Possible reasons are 1. you didn't load React.JS into your page, 2. you loaded it after the above script into your page. Solution is load the JS file before the above shown script.
P.S
Possible solutions.
If you mention react in externals section inside webpack configuration, then you must load react js files directly into your html before bundle.js
Make sure you have the line import React from 'react';
Try to add:
import React from 'react'
import { render } from 'react-dom'
window.React = React
before the render() function.
This sometimes prevents error to pop-up returning:
React is not defined
Adding React to the window will solve these problems.
Adding to Santosh :
You can load React by
import React from 'react'
I know this question is answered. But since what worked for me isn't exactly in the answers, I'll add it here in the hopes that it will be useful for someone else.
My index.js file looked like this when I was getting Uncaught ReferenceError: React is not defined.
import {render} from 'react-dom';
import App from './App';
render(<App />, document.getElementById("root"));
Adding import React from 'react'; at the top of the file fixed it.
Now my index.js looks like this and I don't get any error on the console.
import React from 'react';
import {render} from 'react-dom';
import App from './App';
render(<App />, document.getElementById("root"));
Please note I made no change in webpack.config.js or anywhere else to make this work.
import React, { Component, PropTypes } from 'react';
This may also work!
If you're using TypeScript, make sure that your tsconfig.json has "jsx": "react" within "compilerOptions".
I was facing the same issue.
I resolved it by importing React and ReactDOM like as follows:
import React from 'react';
import ReactDOM from 'react-dom';
I got this error because in my code I misspelled a component definition with lowercase react.createClass instead of uppercase React.createClass.
I got this error because I used:
import React from 'react';
while working with React, Typescript and Parcel
Changing it to:
import * as React from 'react';
Solved the problem as suggested by https://github.com/parcel-bundler/parcel/issues/1199#issuecomment-381817548
Sometimes the order of import can cause this error, if after you have followed all the steps above and still finds it hard on you, try making sure the react import comes first.
import React from 'react'
import { render } from 'react-dom'
before any other important you need to make.
The displayed error
after that import react
Finally import react-dom
if error is react is not define,please add ==>import React from 'react';
if error is reactDOM is not define,please add ==>import ReactDOM from 'react-dom';
To whom using CRA and ended up to this question, can use customize-cra and react-app-rewired packages to override babel presets in CRA.
To do this, create a config-overrides.js in the root and paste this code snippet in it.
const { override, addBabelPreset } = require('customize-cra');
module.exports = override(
addBabelPreset('#emotion/babel-preset-css-prop'),
addBabelPreset([
'#babel/preset-react',
{
runtime: 'automatic',
importSource: '#emotion/react',
},
]),
);
And update scripts in package.json with the ones below.
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom",
I got this because I wrote
import react from 'react'
instead of
import React from 'react'

Categories