Uncaught SyntaxError: Unexpected token in import React from 'react' - javascript

I used to write a react app by using create-react-app and there was no problem. However, I tried to make a small app using only index.html and app.js. Errors were raised in Chrome to import and JSX. For import, Uncaught SyntaxError: Unexpected tokenFor JSX, Uncaught SyntaxError: Unexpected token <Is it because I did not install BABEL or ES6.
I tried to install babel but it still did not work. I also tried adding type="text/babel"
index.html
<!Doctype html>
<html>
<head>
<title>Social Card</title>
<meta charset="utf-8" />
</head>
<body>
<h1>content fahafafafaddha</h1>
<div id="root">
</div>
<script src= "app.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
</body>
</html>
app.js
import React from 'react'
import ReactDOM from 'react-dom'
ReactDOM.render(
<h1> Hello</h1>,
document.getElementById('root')
)

The error is definitely because your code has not been transpiled (which is what babel does). You say that you installed babel..what do you mean by that? You need to configure babel so that it transpiles your code before you run it. create-react-app does it for you by using webpack to transpile, bundle and minify your code.
If you want to learn more about the specifics of how things are working and how to configure your app, Create a new create-react-app, and then run
npm run eject
This will eject all of the previously hidden configurations and help you understand how things are functioning.
UPDATE
One thing you can try is to inst all babel-cli with
npm install --save-dev #babel/core #babel/cli
and then you can use it like
npx babel app.js --out-file app-compiled.js
and use app-compiled to run the server.
UPDATE 2
You are using ES6 syntax (the import statements) as well as JSX (using HTML-ish code in a javascript file). This code cannot be compiled directly by a JS compiler and that's why it's showing you the above error. In order to fix this you need to transpile it into JS that can be read by the browser. There are several ways to do that, some of which are:
Use webpack to transpile, minify, bundle and inject your code into your html.
Use babel-cli to transpile your code manually, and then import the transpiled file instead
Use babel standalone as is explained here
As for what I meant by use app-compiled, I meant include the output file from the babel-cli command (app-compile.js if you ran the command i wrote above) in your html instead of app.js

The order of your <script> tags is important. They are loaded in the order they appear. So your app.js must come after babel and react:
<div id="root"></div>
<!-- DEPENDENCIES MUST COME FIRST -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<!-- Your scripts -->
<script type="text/babel">
const App = () => <h1>Hello React!</h1>;
ReactDOM.render(<App />, document.getElementById('root'));
</script>
Next you can't use import statements when including your dependencies only with script tags. They will simply be available in global namespace. You could maybe use modules too when specifying the type="module" attribute on the script tags but that feature was only fairly recently added and may not be supported by a percentage of currently used browser versions.

Related

what are .esm.js files and whats with the format: 'es' in rollup.js?

I was just going through this library HERE (glide.js) , as i was checking the package.json file i see the following command under the key scripts:
"build:esm": "rollup --config build/esm.js && rollup --config build/esm.modular.js",
What exactly is this script doing ? I know a a config file is being passed to rollup.js here, but whats with the .esm ? when i see the dist/ folder i also see a glide.esm.js file , what exactly is this file doing ?
The build config file for esm looks like below:
import build from './build'
export default Object.assign(build, {
input: 'entry/entry-complete.js',
output: Object.assign(build.output, {
file: 'dist/glide.esm.js',
format: 'es'
})
})
But i don't quite understand what the format: 'es' really means here. Basically to break it down , what is the difference between the glide.js and the glide.esm.js file in the dist/ folder ?
format: 'es' tells rollup that it should output the bundle in an ECMAScript Module aware way. This means that it should create a bundle that can be imported using something along the lines of:
import Glide from "some/place/glide/is/hosted/glide.js
If the context that this script is used in is not ESM aware, you will get syntax errors. In that case, it makes more sense to use a UMD rollup bundle because it is the most compatible version of the bundle.
Explaining UMD in depth is beyond the scope of this question, but suffice it to say that it makes the bundle able to work with AMD and CommonJS aware loaders as well as populating a global namespace with the bundle's exports.
Additionally, for browsers that do not understand what ES modules are or would throw syntax errors if they tried to parse them, you can include a fallback script that would leverage the UMD or bundle of another format using a script of form: <script src="some/non/esm/script.js" nomodule="true" /> which would tell an ESM aware context that it shouldn't run the linked script.
Concrete Example
Consider the following snippet which should work in Firefox and Chrome since they support ESM modules. Stack Overflow snippets do not have a way to load modules so you will need to put together a small project using the following code:
demo.js
import Glide from "https://unpkg.com/#glidejs/glide#3.2.3/dist/glide.esm.js";
new Glide(".glide").mount();
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Module Demo</title>
<link rel="stylesheet" href="https://unpkg.com/#glidejs/glide#3.2.3/dist/css/glide.core.min.css" />
<link rel="stylesheet" href="https://unpkg.com/#glidejs/glide#3.2.3/dist/css/glide.theme.min.css" />
<script type="module" src="demo.js"></script>
</head>
<body>
<main>
<div class="glide">
<div data-glide-el="track" class="glide__track">
<ul class="glide__slides">
<li class="glide__slide">Foo</li>
<li class="glide__slide">Bar</li>
<li class="glide__slide">Fizz</li>
</ul>
</div>
</div>
</main>
</body>
</html>

Integrate React into existing Node express app using CDN

I'm creating a web app using node and react. Rather than seperate Node and React apps I want to integrate React into it. So rather than a react app, I tried importing react CDN into the index.html. My server serves the index.html perfectly, but I'm getting an error in the react component.
this is my index.html
<html>
<head>
<meta charset="utf-8">
<title>React Powered chat App</title>
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js" charset="utf-8"></script>
<script src="/scripts/main.js" charset="utf-8"></script>
<body>
Hello !
<div id ='App'></div>
</body>
</html>
and this is my main.js
class App extends React.Component {
render(){
return (
<div>
Hello !
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('App'));
The error I'm getting is
Uncaught SyntaxError: Unexpected token < main.js:4
What have I done wrong? Isn't it possible to use react with CDN ?
And first when I used react/cjs/react.development libraries I got more errors. Then after reading this stackoverflow question I use /react/umd/ libraries. So what's the difference between cjs and umd CDN libraries ?
The code doesn't work because react uses JSX (HTML inside javascript), which cannot be read by the browser and needs to be transpiled to ordinary javascript which can be read by browsers. One such transpiler is babel. Your code doesn't work due to the absence of transpiler.
You can use create-react-app, which comes bundled with the transpiler and everything that you'll need to get started with react. And as I understand, since you want to add your express backend, here is a tutorial that will help you get started with attaching create-react-app to your express backend. Hope this helps.
Since JSX (the HTML code sprinkled in the JavaScript) is not regular JavaScript or ES6 code, you cannot load it directly in your browser.
So the problem is not getting the React library from a CDN, that’s fine.
The problem is that you have to transpile your main.js file to regular JavaScript code, for example using Babel.
The most commonly used tool to do this transpilation with Babel automatically is webpack.
If you don’t want to learn how to set up webpack and Babel in detail, I recommend to use create-react-app, this takes the burden of setting up all of the boilerplate from your shoulders and creates a JavaScript bundle that you can use directly in your browser.
Note: if you do end up using create-react-app, you don’t need to get the React lib from a CDN, it will already be included in the bundle.
You also need to add babel cdn in the Html file which would convert JSX to JS
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>

How to import bootstrap or external js in Vue.js

Few days ago i decide to implement vue.js in a simple html5, css3 and javascript web. But now i can't import my libraries like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>LiloTechnology</title>
<link href="/css/bootstrap.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
<script type="text/javascript" src="../assets/js/jquery.1.8.3.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap.js"></script>
<script type="text/javascript" src="../assets/js/jquery-scrolltofixed.js"></script>
<script type="text/javascript" src="../assets/js/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="../assets/js/jquery.isotope.js"></script>
<script type="text/javascript" src="../assets/js/wow.js"></script>
<script type="text/javascript" src="../assets/js/classie.js"></script>
</body>
</html>
Can you please tell me how to import external .js files?
Thank you.
You can just add external (from the outside) resources like so:
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
and so on... CSS works the same way in link rel="externalUrlTo.css"
For a production ready app; maybe consider using a module bundler like Webpack and npm to install dependencies. Therefore you don't have to rely on a external services being up or down and have tighter control over bundling.
If you are in a ES6 or ES5-style CommonJS environment and using Webpack, you should consider installing your dependencies with npm
npm install module --save
and afterwards importing them in your JS code using var module = require('module') or in ES6 import module from 'module'
For instance for jQuery it would be npm install jquery --save (--save by the way stores it to your package.json to be able to restore your dependencies easily using npm install) and import it using var $ = require('jquery') (again ES6: import {$, jQuery} from 'jquery').
For jQuery in particular take into account, that some libraries rely on it being globally available. So make sure to import it first and assign it to window (or global) as seen in How to import jquery using ES6 syntax?)
If you require a specific version you might also want to add it to your package.json or install it directly using npm install module#version. Hope that helps a bit!

How to make ReactJS JSX's work on electron

I've wanted to create simple desktop app which uses React JS for data presentation.
However, I'm overwhelmed with so many modules and technologies. There is an electron react boilerplate which very complicated for starters like me.
I have simple project with these libs:
electron as dev
react
react-dom
I have main.js in my root path of my project which launches electron and it is taken from this quickstart example
I have index.html file where my JSX should be loaded:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<div id="react-view"></div>
</body>
<script type="text/jsx">
// You can also require other files to run in this process
require('./scripts/application');
</script>
</html>
There are scripts/application.js file where my JSX will be populated to my <div id="react-view"></div>.
My App.jsx is very simple:
import React, {Component} from 'react'
class App extends Component{
render() {
return <h1>Hello From React</h1>;
}
}
export default App;
My application.js file looks like this:
import React from 'react';
import ReactDom from 'react-dom/server';
import App from 'components/App';
ReactDom.render(<App/>, document.getElementById("react-view"));
When I launch my electron application it opens me a window with empty content, which means that my JSX is not loaded. And it does not throw any error messages
What did I miss?
Here is the problem - no one understands JSX except a transpiler.
Two ways, you can get JSX work -
use a browser based/client side transpiler (use only for development
purpose)
include this file as a script tag
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.js"></script>
use type="text/babel" on your script tag which loads your JSX
<script type="text/babel" src="index.js"></script>
checkout the sample here - https://github.com/rabibiswal/reactdemo/tree/master/hello-world-jsx
user a server based transpiler - e.g. Babel
You can use different tools like webpack etc.
checkout the sample here -
https://github.com/rabibiswal/reactdemo/tree/master/hello-world-react-es5
You need to install node and use npm install and npm run build to get this code working

NW.js + Babel: ES6 import working but not export?

I'm building a NW.js app, currently with babel-standalone and React. I can use ES6 import, but ES6 export on the other hand does not work, console spits out unexpected token export. What's going on?
index.html:
<html>
<head>
<meta charset="utf-8">
<script src="assets/react.min.js" charset="utf-8"></script>
<script src="assets/react-dom.min.js" charset="utf-8"></script>
<script src="assets/babel.min.js" charset="utf-8"></script>
</head>
<body>
<script type="text/babel" src="script/App.js"></script>
</body>
</html>
(yes, Babel indeed works, since React stuff inside runs OK)
In app.js:
import Lib from "./script/lib.js";
(and it's indeed exporting lib.js correctly, since that is the file responsible for the error)
In script/lib.js:
export default class {...};
I'm aware I can use Node modules instead, or even HTML script loading, but that's beside the point. I want to know why export doesn't work even if Babel doesn't seem to be broken, and even import works fine.
The problem is that Babel doesn't see files that were loaded via require, and they are loaded as they are, without transpilation.
There can be several ways to work this around, but the easiest one will be using Babel at build step.
Process your source code and then load processed code nw.js environment. The example how to do that you can find at this boilerplate project

Categories