Syntax error in ReactJS - javascript

I'm starting to learn ReactJS and I'm following instructions in a book on getting started. My directory structure looks like this:
app/App.js
node_modules
index.html
package.json
webpack.config.js
I think that the culprit of the problem is this error message from CLI:
ERROR in ./app/App.js
Module build failed: SyntaxError: c:/code/pro-react/my-app/app/App.js: Unexpected token (6:6)
4 | render() {
5 | return (
> 6 | <h1>Hello World</h1>
| ^
7 | );
8 | }
9 | }
The contents of App.js are:
import React from 'react';
class Hello extends React.Component {
render() {
return (
<h1>Hello World</h1>
);
}
}
React.render(<Hello />, document.getElementById('root'));
Here is the contents of package.json:
{
"name": "my-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node_modules/.bin/webpack-dev-server --progress",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.4.5",
"babel-loader": "^6.2.1",
"webpack": "^1.12.11",
"webpack-dev-server": "^1.14.1"
},
"dependencies": {
"react": "^0.14.6"
}
}
And the contents of webpack.config.js are:
module.exports = {
entry: __dirname + "/app/App.js",
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel'
}]
}
};
I launch the application from CLI with the command:
npm start
And when I go to http://localhost:8080 in Dev Tools there is an error message:
GET http://localhost:8080/bundle.js 404 (Not Found)
But as I said, I think that the culprit is that it doesn't like the syntax so it doesn't make the bundle.js file. Please let me know what I'm doing wrong.

I think it happens because you are using babel-6 without babel presets, in this case you need babel-preset-es2015 and babel-preset-react.,
# For ES6/ES2015 support
npm install babel-preset-es2015 --save-dev
# Fot JSX support
npm install babel-preset-react --save-dev
then change webpack config
{
test: /\.jsx?$/,
loader: 'babel',
query: {
presets: ['es2015', 'react'],
}
}
or instead of using query you can create .babelrc file with content
{
"presets": ["es2015", "react"]
}
also you need install react-dom and use ReactDOM.render instaed or React.render

Related

Webpack/Babel installation for ReactJS

I just started learning ReactJS and came across something called as webpack which is basically a module bundler.
Somehow,I'm stuck with the configuration of the same and the following error keeps coming.
ERROR in ./src/index.js 7:16
Module parse failed: Unexpected token (7:16)
You may need an appropriate loader to handle this file type.
render()
{
return (<div> <h1> Hi </h1> </div>);
}
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! reactsetup#1.0.0 start: webpack --mode=development ./src/index.js -o bundle.js
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the reactsetup#1.0.0 start script.
Here is my Package.json
{
"name": "reactsetup",
"version": "1.0.0",
"main": "./src/index.js",
"dependencies": {
"babel-preset-es2015": "^6.24.1",
"bundle-loader": "^0.5.6",
"react": "^16.4.1",
"react-dom": "^16.4.1"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"webpack": "^4.12.0",
"webpack-dev-server": "^3.1.4"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack --mode=development ./src/index.js -o bundle.js",
"build": "webpack -d && cp index.html dist/index.html && webpack-dev-server --content-base src/ --inline --hot",
"dev-start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"description": ""
}
index.js
import React from "react"
import {render} from "react-dom"
class App extends React.Component {
render()
{
return (<div> <h1> Hi </h1> </div>);
}
}
render(<App/>, window.document.getElementById("app"));
web.config.js
var path = require("path");
var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");
var config = {
entry: SRC_DIR + "index.js",
output: {
path: DIST_DIR,
filename: "bundle.js"
},
module: {
rules: [ {
test: /\.js?/,
use: {
loader: "babel-loader",
exclude: /node_modules/,
query: {
presets: ["react", "es2015"]
}
}
}
]
}
};
module.exports = config
And lastly, index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
PS: This is my first question ever on stackoverflow. Apologies for the flaws,if any.
It seems there are a couple of things
rename web.config.js to webpack.config.js
install babel-preset-react
change your HTML to the following
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="app"></div>
<script src="./dist/bundle.js"></script>
</body>
</html>
webpack.config.js
var path = require('path');
var DIST_DIR = path.resolve(__dirname, 'dist');
var SRC_DIR = path.resolve(__dirname, 'src');
var config = {
entry: SRC_DIR + '/index.js',
output: {
path: DIST_DIR,
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js?/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['react', 'es2015'],
},
},
},
],
},
};
module.exports = config;
One tip, use create react app to start fast with react :)
the default name for config is "webpack.config.js", not the "web.config.js". And you don't pass the "--config" property either. So it looks like your webpack config is not used at all.
I believe, renaming config to the "webpack.config.js" could help you
The easiest way for a beginner to set-up the React environment is to use create-react-app.
I'm assuming that you already have node installed. If not a quick Google search will instruct you how to install nodejs.
After that run the following command in the directory where you want to create the project
npm install -g create-react-app
create-react-app my-app
cd my-app
npm start
Then open your browser and go to localhost:3000 and you should see your react template.
More information on create-react-app can be found via the following links
github page
react official documentation

Cannot find module "./foo.css" when using webpack as script

I'm need to use webpack as a script (not the typical config file) and be able to support css imports, however webpack/style-loader does't seem to be able to load a css import when it's outside the root directory.
directoryA/package.json
{
"name": "poc",
"version": "1.0.0",
"description": "",
"main": "poc.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"style-loader": "^0.28.8",
"style-loader": "^0.19.1",
"webpack": "^3.10.0"
}
}
directoryA/poc.js
const path = require("path");
const webpack = require("webpack");
let appPath = process.env.PWD;
webpack({
entry: path.join(appPath, 'app.js'),
context: appPath,
output: {
libraryTarget: 'umd',
path: path.join(appPath, 'out'),
filename: 'app.js'
},
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
}
}).run(() => {
console.log("done");
});
directoryB/app.js
import './foo.css';
directoryB/foo.css
body { background-color: blue; }
directoryB/out/index.html
<html>
  <head><script src="app.js"></script></head>
<body></body>
</html>
steps to replicate:
cd directoryB/
node ../directoryA/poc.js
then open directoryB/out/index.html in the browser
result: "Error: Cannot find module "./foo.css"
expected: loading css style and getting a blue page
Note that, if out/index.html , app.js and foo.cs are inside directoryA instead, then running node poc.js actually yields the expected result, however outside, webpack or style-loader can't seem to find the file (note: also tried to use the modules: directive. both cases work if using importing a js file)

Simple Webpack + React + ES6 + babel example doesn't work. Unexpected token error

am getting a parsing error while running webpack to compile the jsx syntax. Would appreciate if someone could point me to the error. I see a similar question asked Webpack, React, JSX, Babel - Unexpected token < but the solution suggested there doesn't work for me.
This is how my config files look like:
package.json
{
"name": "dropdowns",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"react": "^15.2.1",
"react-dom": "^15.2.1",
"babel-core": "^6.11.4",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.11.1"
},
"devDependencies": {
"webpack": "^1.13.1",
"webpack-dev-server": "^1.14.1"
},
"author": "",
"license": "ISC"
}
my webpack.config.js file is
module.exports = {
context: __dirname + "/app",
entry: "./main.js",
output: {
filename: "bundle.js",
path: __dirname + "/dist"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
};
In a local app folder I have main.js and IdMappingOptions.js as follows:
// in IdMappingOptions.js
import React from 'react';
class IdMappingOptions extends React.Component {
render () {
return <span>Hello!</span>
}
}
export default IdMappingOptions;
// in main.js
import React from 'react';
import { render } from 'react-dom';
import IdMappingOptions from './IdMappingOptions';
render(
<IdMappingOptions/>, document.body
);
when running node_modules/.bin/webpack I get the following error trace:
Hash: 396f0bfb9d565b6f60f0
Version: webpack 1.13.1
Time: 37ms
[0] ./main.js 0 bytes [built] [failed]
ERROR in ./main.js
Module parse failed: /scratch/parallel/repository/dropdowns/app/main.js Unexpected token (6:4)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (6:4)
at Parser.pp.raise (/scratch/parallel/repository/dropdowns/node_module/acorn/dist/acorn.js:923:13)
Edit:
as per the comments below fixed the test pattern and added babel-core in the webpack.config.js. Here is my
Your test seems faulty:
test: "/.js$"
Try this:
test: /\.js$/
You need babel-core to use babel in your project. (https://github.com/babel/babel-loader#installation).
npm install --save-dev babel-core

Uncaught ReferenceError: Main is not defined with webpack/react in Rails 4.2.4

I'm facing the error below from Chrome Canary even the webpack works. By the way "Main" is my component created with React 0.14.6
VM601:1 Uncaught ReferenceError: Main is not defined
(anonymous function) # VM601:1
mountComponents # react_ujs_mount.self-69e74f4….js?body=1:56
(anonymous function) # react_ujs_native.self-69da92a….js?body=1:9
fire # jquery.self-660adc5….js?body=1:3233
fireWith # jquery.self-660adc5….js?body=1:3363
ready # jquery.self-660adc5….js?body=1:3583
completed # jquery.self-660adc5….js?body=1:3618
Do you know if I need to install or set up something else?
Below, you can find installation and configuration that I have in my OS X Yosemite 10.10.5
Webpack
When I run the "webpack" inside my test app, i got the message below. Seems to be that it looks good.
ash: f9147c799d98d76fbd61
Version: webpack 1.12.14
Time: 624ms
Asset Size Chunks Chunk Names
bundle.js 5.76 kB 0 [emitted] main
+ 2 hidden modules
Babel installation
babel-core#6.7.4
babel-code-frame#6.7.4
babel-generator#6.7.2
babel-helpers#6.6.0
babel-messages#6.7.2
babel-register#6.7.2
babel-runtime#5.8.38
babel-template#6.7.0
babel-traverse#6.7.4
babel-types#6.7.2
babel-loader#6.2.4
babel-preset-es2015#6.6.0 extraneous
babel-preset-react#6.5.0 extraneous
babel-preset-stage-0#6.5.0 extraneous
During my babel installation, i got the message below.
npm ERR! peer dep missing: webpack#1 || ^2.1.0-beta, required by babel
loader#6.2.4
That appeared when I installed
webpack
babel-loader
babel-preset-es2015
babel-preset-react
babel-preset-stage-0
babel loader through
Another question. Do you know if this could be affecting the generation of the bundle?
.babelrc
{
"presets": ["es2015", "stage-0", "react"]
}
webpack.config.js
module.exports = {
entry: "./app/assets/frontend/main.jsx",
output: {
path: __dirname + "/app/assets/javascripts",
filename: "bundle.js"
},
resolve: {
extensions: ['','.js','.jsx']
},
module: {
loaders: [
{ test: /\.jsx$/, loader: "babel-loader" }
]
}
};
greet.jsx
export default class Greet extends React.Component {
render() {
return <h2>Hello World</h2>;
}
}
main.jsx
import Greet from './greet';
class Main extends React.Component {
render() {
return (
<Greet />
);
}
}
let documentReady = () => {
ReactDOM.render(
<Main />,
document.getElementById('react')
);
};
$(documentReady);
index.html.erb
<div id="react"/>
<%= react_component("Main") %>
package.json
{
"name": "twitter-clone",
"version": "1.0.0",
"description": "Twitter clone, written in React, Flux, and Rails",
"main": "index.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Jose Alanya",
"license": "ISC",
"dependencies": {
"babel-core": "^6.7.4",
"babel-loader": "^6.2.4"
},
"devDependencies": {
"babel-core": "^6.7.4",
"babel-loader": "^6.2.4"
}
}
Thanks for your prompt answer.
You'll need to do few things to get the react-rails gem working with Webpack, you might be able to get it done by adding this line at the end of your Main.jsx
window.Main = Main;
However, I think the gem needs all files in a certain location if I remember correctly.
There is another gem that supports Webpack out of the box: react_on_rails
Do you have configured:
Rails.application.config.assets.precompile += %w( bundle.js)
in your assets initilizer file? Besides I think you need the "export default" statement for the Main component.

Webpack and React -- Unexpected token

I am new to React and Webpack. I am setting up my first project, when I try to run the webpack-dev-server my code does not compile!
Update
Answer below is correct. I needed to add 'react' to babel loader presets. You can see the full source for project here: https://github.com/cleechtech/redux-todo
Error:
$ webpack-dev-server
http://localhost:8080/webpack-dev-server/
webpack result is served from /
content is served from ./dist
Hash: d437a155a1da4cdfeeeb
Version: webpack 1.12.14
Time: 5938ms
Asset Size Chunks Chunk Names
bundle.js 1.51 kB 0 [emitted] main
chunk {0} bundle.js (main) 28 bytes [rendered]
[0] multi main 28 bytes {0} [built] [1 error]
ERROR in ./src/index.js
Module build failed: SyntaxError: /Users/connorleech/Projects/redux-todo/src/index.js: Unexpected token (7:16)
console.log(ReactDOM);
ReactDOM.render(<App />,document.getElementById('root'));
src/index.js:
var react = require('react');
var ReactDOM = require('react-dom');
var App = require('./components/App');
console.log(ReactDOM);
ReactDOM.render(<App />,document.getElementById('root'));
src/components/App.js
var React = require('react');
var App = React.createClass({
render: function() {
return (
<div>
<h1>I am app!</h1>
</div>
);
}
});
console.log(App);
module.exports = App;
dist/index.html
<!doctype html>
<head>
<title>Redux todo</title>
</head>
<body>
<h1>Hello world</h1>
<div id='root'></div>
<script src='bundle.js'></script>
</body>
And finally here is my webpack config and package.json:
module.exports = {
// starting point
entry: [
'./src/index.js'
],
module: {
loaders: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel', // 'babel-loader' is also a legal name to reference
query: {
presets: ['es2015']
}
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
// create bundle.js file
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './dist'
}
};
package.json
{
"name": "redux-todo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/cleechtech/redux-todo.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/cleechtech/redux-todo/issues"
},
"homepage": "https://github.com/cleechtech/redux-todo#readme",
"dependencies": {
"react": "^0.14.8",
"react-dom": "^0.14.8",
"react-redux": "^4.4.1",
"redux": "^3.3.1"
},
"devDependencies": {
"babel-core": "^6.7.4",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"webpack": "^1.12.14"
}
}
You also need to add the react preset into your babel-loader config
And it must come after the es2015
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel', // 'babel-loader' is also a legal name to reference
query: {
presets: ['es2015', 'react']
}
}
The problem you're experiencing happens because for babel to know how to transpile JSX - it should know its syntax, which it does not out of the box.
As it was mentioned in the comments - you would also have to install the babel-preset-react npm package (which would obvious anyway since the babel would tell it to you on the first run anyway).
References:
https://babeljs.io/docs/plugins/preset-react/

Categories

Resources