Learning ReactJS: Uncaught SyntaxError: Unexpected token import - javascript

I'm new to ReactJS. I'm trying out the code from egghead.io and I keep getting the following error:
Uncaught SyntaxError: Unexpected token import
I have loaded babel twice now and have followed along the lesson as described, but it just won't load into the html page. Here is the codes:
index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>Setup</title>
</head>
<body>
<div id = "app"></div>
<script src = "main.js"></script>
</body>
</html>
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App2';
ReactDOM.render(<App />, document.getElementById('app'))
app2.jsx
import React from 'react';
import ReactDom from 'react-dom';
class App extends React.Component {
render(){
let txt = this.props.txt
return <h1>{txt}</h1>
}
}
App.propTypes = {
txt: React.PropTypes.string,
cat: React.PropTypes.number.isRequired
}
App.defaultProps = {
txt: 'this is the default txt'
}
ReactDOM render(
<App cat={5}/>,
document.getElementById('app')
)
package.json
{
"name": "es6-react-setup",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^0.14.3",
"react-dom": "^0.14.3"
},
"devDependencies": {
"babel-core": "^6.14.0",
"babel-loader": "^6.2.5"
}
}
Please help.

After installing the Babel presets for ES6 and React you need to enable them either by creating a .babelrc file or by opting in in your package.json file.
(Confusing) docs here: http://babeljs.io/docs/usage/babelrc/
Example package.json entry enabling the presets:
"babel": {
"presets": [
[
"env",
{
"modules": false
}
],
"react"
]
}

import is the ES6 syntax. You need to npm install babel-preset-es2015 babel-preset-react --save-dev to tell babel compile your ES6 and React code.
you can load 2 packages in your webpack.config.js file :
module.exports = {
entry: './main.js',
output: {
path: './',
filename: 'index.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
I hope it will help you.

Related

React component error: expected a string or a class/function but got undefined

I am getting the following error in a create-react-app. Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
The app is currently a super-basic - it just imports and renders one single component:
import './App.css';
import { PasswordInput } from 'gg-react-test-lib';
function App() {
return (
<div className="App">
<PasswordInput />
</div>
);
}
export default App;
I am therefore assuming that the problem is with my component library that I am importing the PasswordInput component from. I am installing it from NPM.
It has an index.js file like:
import Radio from './Radio/Radio';
export { PasswordInput, Radio }```
Those component files themselves do a default export at the bottom of the file e.g.:
`export default PasswordInput;`
I have a pretty minimal webpack.config.js file in my component library repo:
```const TerserPlugin = require('terser-webpack-plugin');
const path = require('path');
module.exports = {
mode: 'production',
entry: './src/index.js',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader"
}
]
},
output: {
path: path.resolve(__dirname, "dist/"),
filename: 'bundle.js'
},
optimization: {
minimizer: [new TerserPlugin()]
},
};
My package.json:
{
"name": "gg-react-test-lib",
"version": "1.0.7",
"description": "",
"main": "dist/bundle.js",
"module": "src/index.js",
"author": "",
"license": "ISC",
"dependencies": {
"clsx": "^1.0.4",
"node-sass": "^4.13.0",
"react": "^16.12.0",
"react-dom": "^16.12.0"
},
"scripts": {
"build": "webpack"
},
"devDependencies": {
"#babel/cli": "^7.7.5",
"#babel/core": "^7.7.5",
"#babel/preset-react": "^7.7.4",
"babel-loader": "^8.0.6",
"webpack": "^4.41.3",
"webpack-cli": "^3.3.10"
}
}
.babelrc file:
{
"presets": [
"#babel/preset-react"
]
}

ReactJS code compiled successfully , but not printing on Browser

After a lot of efforts i was able to install and configure ReactJS. After executing "npm start" command, the code was "COMPILED SUCCESSFULLY" and redirected me to the web browser.
But there wasn't any output, ie., the browser was "blank".
Can anyone resolve this?? ( my first post here )
Also check the code that i have used..
index.html file
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src = 'index_bundle.js'></script>
</body>
</html>
App.js
import React, { component } from 'react';
class App extends Component {
render(){
return(
<div>
<h1> Hello World</h1>
<p>Hello </p>
</div>
);
}
}
export default App;
main.js
import React from 'react';
import { render } from 'react-dom';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App />, document.getElementById('app'));
package.json snippet
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './main.js',
output: {
path: path.join(__dirname, '/bundle'),
filename: 'index_bundle.js'
},
devServer: {
inline: true,
port: 8001
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins:[
new HtmlWebpackPlugin({
template: './index.html'
})
]
}
The only issue is the output is not getting displayed on browser..
command prompt
COMMAND PROMPT AFTER "npm start"
browser
output not displaying
Add an .babelrc file in root folder with following:
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
And package.json is expected to include following dependencies:
"devDependencies": {
"#babel/core": "^7.4.0",
"#babel/preset-env": "^7.4.2",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.1",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"react": "^16.8.5",
"react-dom": "^16.8.5",
"style-loader": "^0.23.1",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"webpack-dev-server": "^3.2.1"
}
Update
Also update webpack.config.js to:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./main.js",
output: {
path: path.join(__dirname, "/bundle"),
filename: "index_bundle.js"
},
devServer: {
inline: true,
port: 8001
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./index.html"
})
]
};
Check the path and change Component to component.
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Route path="/" component={HomePage} exact />
</div>
</Router>
);
}
}

Cannot import materialize-css in React project to use Chips

I have created project by command:
create-react-app app
I am using materialize-css http://materializecss.com/ and want to use Chips http://materializecss.com/chips.html.
import React, { Component } from 'react';
import $ from 'jquery';
import 'materialize-css';
class Form extends Component {
constructor(props) {
super(props);
$(document).ready(function() {
$('.chips').material_chip({
data: [{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}],
});
});
}
render() {
return (
<div>
<div className="chips"></div>
<button>Add</button>
</div>
)
}
}
I have tried to import:
import 'materialize-css/bin/materialize.css'
import 'materialize-css/bin/materialize.js'
But it's not working. The browser throw error:
Uncaught TypeError: $(...).material_chip is not a function
Try this in your entry JS file
import 'materialize-css'; // It installs the JS asset only
import 'materialize-css/dist/css/materialize.min.css';
and you are done!
Update:
I have put all the necessary details to get your code working. Try this out
index.jsx file is here
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import 'materialize-css';
import 'materialize-css/dist/css/materialize.min.css';
class Form extends Component {
constructor(props) {
super(props);
$(document).ready(function() {
$('.chips').material_chip({
data: [{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}],
});
});
}
render() {
return (
<div>
<div className="chips"></div>
<button>Add</button>
</div>
)
}
}
ReactDOM.render(<Form />, document.getElementById('app'));
and package.json is like
"dependencies": {
"babel-preset-react": "^6.16.0",
"css-loader": "^0.26.1",
"font-loader": "^0.1.2",
"jquery": "^3.1.1",
"materialize-css": "^0.97.8",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"redux": "3.6.0",
"style-loader": "^0.13.1"
},
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.21.0",
"babel-loader": "^6.2.10",
"babel-preset-es2015": "^6.18.0",
"webpack": "^1.14.0",
"webpack-dev-server": "^1.16.2",
"webpack-hot-middleware": "^2.15.0"
}
and webpack.config.js is
const webpack = require('webpack');
module.exports = {
entry: [Screenshot from 2017-01-15 18-11-16
"./src/index.jsx",
"webpack-dev-server/client?http://localhost:3000/",
"webpack/hot/only-dev-server"
],
output: {
filename: "bundle.js",
path: __dirname + '/public'
},
devServer: {
contentBase: './public',
port: 3000
},
// Bundle lookup dir for included/imported modules
// By default, bundler/webpack with search here for the scripts
resolve: {
modulesDirectories: ['node_modules', 'src'],
extensions: ['', '.js', '.jsx']
},
// make sure you added babel-loader to the package
// npm i babel-loader babel-core babel-preset-es2015 -D
module: {
loaders: [
{
test: /\.js[x]?$/, // Allowing .jsx file to be transpiled by babel
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
},
{ test: /\.css$/, loaders: [
'style',
'css?importLoaders=1',
'font?format[]=truetype&format[]=woff&format[]=embedded-opentype'
] },
{ test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader?name=fonts/[name].[ext]' }
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
};
No error whatsoever.
With NPM:
Step 1: Install materialize
If you are using npm, make sure you install materialize using the command listed in their documentation:
npm install materialize-css#next
DON'T MISS the '#next' at the end. The installed version will be something like: "^1.0.0-rc.2" OR "^1.0.0-alpha.4"
Step 2: Import materialize:
import 'materialize-css/dist/css/materialize.min.css'
import M from 'materialize-css/dist/js/materialize.min.js'
OR
import 'materialize-css/dist/css/materialize.min.css'
import M from 'materialize-css'
In order for the css import to work, you would need a css loader. Note that this loader is already included in projects built using create-react-app so you don't need the next steps. If instead, you are using custom webpack config, then run:
npm install --save-dev style-loader css-loader
Now add css-loader and style-loader in webpack config
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.join(__dirname, "build")
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /.js$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["env", "react"]
}
}
}
]
}
}
Now you can initialize components individually, or all at once using M.AutoInit();
With CDN:
Add the following in your HTML file.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
Then, in the webpack config, add externals: https://webpack.js.org/configuration/externals/

How do I correct this react syntax error?

I am working on a practice application in reactjs and I am getting this error that I have been unable to figure out even with perusing through SO:
ERROR in ./App.js
Module build failed: SyntaxError: Unexpected token, expected , (6:13)
4 | render(){
5 | return (
> 6 | <li>{{this.props.name}}</li>
| ^
7 | )
8 | }
9 | }
# ./main.js 11:11-27
These are the files:
webpack.config.js:
module.exports = {
entry: './main.js',
output: {
path: './',
filename: 'index.js'
},
devServer: {
inline: true,
port: 3000
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
package.json:
{
"name": "react-test",
"version": "1.0.0",
"description": "react test application",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "Daniel Cortes",
"license": "ISC",
"dependencies": {
"react": "^15.4.0",
"react-dom": "^15.4.0"
}
}
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/paper/bootstrap.min.css">
<style type='text/css'>
body, input {
font-size: 24px !important;
}
</style>
</head>
<body>
<div id="app" class="container-fluid"></div>
<script src='index.js'></script>
</body>
</html>
App.js:
import React from 'react';
import ReactDOM from 'react-dom';
class Channel extends React.Component {
render(){
return (
<li>{{this.props.name}}</li>
)
}
}
export default Channel
main.js:
import React from 'react';
import ReactDOM from 'react-dom';
import Channel from './App';
ReactDOM.render(<Channel name='Hardware Support' />, document.getElementById('app'));
In App.js, simply pass the expression this.props.name rather than {this.props.name} as the desired value:
render(){
return (
<li>{this.props.name}</li>
)
}

I am getting a 404 error on my new Reactjs app, is it looking for a main.js file?

This app should be rendering what I have here (/Users/ldco2016/Projects/reactquiz/src/components/App.jsx:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
class App extends Component{
render(){
return(
<div>
APP
</div>
)
}
}
export default App
but instead I get a blank page and the Chrome Dev tools console is telling me this:
GET http://localhost:8080/app/js/main.js 404 (Not Found)
I know what that means but I am unclear as to whether it is trying to find the page I want to render or the main.js file.
/Users/ldco2016/Projects/reactquiz/package.json:
{
"name": "reactquiz",
"version": "1.0.0",
"description": "A Reactjs Quiz App",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Daniel Cortes",
"license": "ISC",
"devDependencies": {
"babel-core": "6.13.*",
"babel-loader": "6.2.*",
"webpack": "1.13.*"
},
"dependencies": {
"react": "^15.3.1",
"react-dom": "^15.3.1"
}
}
/Users/ldco2016/Projects/reactquiz/app/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reactjs Quiz</title>
</head>
<body>
<div id="app"></div>
<script src="js/main.js"></script>
</body>
</html>
ldco2016#DCortes-MacBook-Pro-3 ~/Projects/reactquiz/webpack.config.js:
module.export = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
filename: 'app/js/main.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel',
exclude: /node_modules/
}]
}
}
/Users/ldco2016/Projects/reactquiz/src/index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.jsx';
ReactDOM.render(
<App />,
document.getElementById('app')
);
You need to run webpack to generate the main.js file. Make two changes to your file first in package.json add a script "start": "webpack --progress -p --config webpack.config.js --watch" and in your webpack.config.js change the loader to babel-loader.
P.S. Second change may not be required.
package.json
{
"name": "reactquiz",
"version": "1.0.0",
"description": "A Reactjs Quiz App",
"main": "index.js",
"scripts": {
"start": "webpack --progress -p --config webpack.config.js --watch"
},
"author": "Daniel Cortes",
"license": "ISC",
"devDependencies": {
"babel-core": "6.13.*",
"babel-loader": "6.2.*",
"webpack": "1.13.*"
},
"dependencies": {
"react": "^15.3.1",
"react-dom": "^15.3.1"
}
}
webpack.config.js
module.export = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
filename: 'app/js/main.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
}]
}
}
Now run webpack with command
npm run start
now open your localhost and the above should work.

Categories