(ReactJS,Babel,Webpack,NodeJS) Uncaught SyntaxError: Unexpected token import - html

I have been killing myself over this to work for days, but to no avail.
I am using ReactJS and Babel. I have node JS installed as well as webpack.
It is a simple Hello World app.
The error I get is:
Uncaught SyntaxError: Unexpected token import
Here is the source code:
package.json
{
"name": "app",
"version": "1.0.0",
"main": "webapp.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-preset-react": "^6.3.13",
"express": "^4.15.3",
"react": "^15.5.4",
"react-dom": "^15.5.4"
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"webpack": "^2.5.1"
},
"description": ""
}
webpack.config.js
var path = require('path');
module.exports = {
entry: './webapp.js',
output: {
path: './',
filename: 'index.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
webapp.js
var express = require('express')
var app = express();
app.use(express.static('static'));
var server = app.listen(3000, function() {
var port = server.address().port;
console.log("Started server at port", port);
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/javascript" src="App.js">
</script>
</body>
</html>
App.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);

Your webpack is configured to build webapp.js source. This is server side node applications. So add this:
target: "node"
to your webpack config.
This option enable node build environment.
In order to build client application you need another configuration.
The webpack config must have
target: "web"
entry: './App.js',
And your html must have:
<script type="text/javascript" src="index.js">
instead of
<script type="text/javascript" src="App.js">
Because browser can not understand modern syntax. And you need to build and load compiled js bundle.

To add to what oklas mentioned,
I noticed that you have:
test: /\.js$/,
instead you should have:
test: /\.jsx?/,
(because the react preset is looking for jsx in order to transpile it to js)
If after that change you still have issues, I'd recommend npm i -D the latest babel presets, as follows:
module.exports = {
mode: 'development',
target: 'web',
entry: `${SRC_DIR}\\app.jsx`,
output: {
filename: CHANGE_ME,
path: DIST_DIR
},
module: {
rules: [
{
test: /\.jsx?/,
include: SRC_DIR,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['#babel/preset-react', '#babel/preset-env']
}
},

Related

HTML & CSS works in the development mode but CSS is missing in the production mode

I am completely new in this field.I apologize for any mistakes. I am working on a node js project using webpack, HTML loader. I am using dev server dependency to test in the localhost. All the models and views and the template index.html files are located in the 'src' folder. The webpack config and package json and the server.js files are located in the root directory. The webpack HTML loader is used to load index.html file in the 'dist' folder. In the 'dist' folder, there is a folder called css and inside of it style.css is located.
Everything works in the development mode and I can run the page in my localhost but problem starts when I try to run "npm run start" which actually includes "node server.js". And then when I try to access the page in the localhost then the styling of the page does not work but the interactive behavior of the page works fine. I think, the 'href' that links the css in the index.htm file is not correct.
Does anybody have idea what is wrong in my code? I have attached all the images and code that I am using.
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: ['./src/js/index.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/bundle.js'
},
devServer:{
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use:{
loader: 'babel-loader'
}
}
]
}
}
package.json file
{
"name": "forkify",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack --mode development",
"dev-start": "webpack-dev-server --mode development --open",
"heroku-postbuild": "webpack --mode production",
"start": "node server.js"
},
"author": "Sayeedur Rahman",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.9.0",
"#babel/preset-env": "^7.9.5",
"babel-loader": "^8.1.0",
"html-webpack-plugin": "^4.2.0",
"webpack": "^4.20.2",
"webpack-cli": "^3.1.1",
"webpack-dev-server": "^3.10.3"
},
"dependencies": {
"axios": "^0.19.2",
"core-js": "^3.6.5",
"express": "^4.17.1",
"fractional": "^1.0.0",
"regenerator-runtime": "^0.13.5",
"uniqid": "^5.2.0"
},
"engines": {
"node": "12.16.1",
"npm": "6.13.4"
}
}
server.js file
const express = require('express');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
app.use(express.static(__dirname + '/dist'));
app.get('/', (req, res) =>{
res.sendFile(path.resolve(__dirname, '/dist', 'index.html'))
});
app.listen(port);
console.log(`server started on ${port}`);
index.html file section
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/css?family=Nunito+Sans:400,600,700" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
<link rel="shortcut icon" href="img/favicon.png" type="image/x-icon">
<title>forkify // Search over 1,000,000 recipes</title>
</head>
I'm not sure if this works but try adding this line after your routes in the server.js file:
app.use(express.static(path.resolve(__dirname, './dist')));
Also note the dot befor /dist
If this doesn't work try changing the following line in your index.html:
<link rel="stylesheet" href="../../css/style.css">
or
<link rel="stylesheet" href="../css/style.css">

gulp: Module parse failed

I'm working with Laravel 5.3.
Errors I get after installing node-uuid.
{ [Error: ./~/diffie-hellman/lib/primes.json
Module parse failed: /var/www/html/filecloudprod/node_modules/diffie-hellman/lib/primes.json Unexpected token (2:11)
You may need an appropriate loader to handle this file type.
My package.json file. Note json-loader
{
"private": true,
"scripts": {
"prod": "gulp --production",
"dev": "gulp watch"
},
"devDependencies": {
"gulp": "^3.9.1",
"jquery": "^3.1.0",
"laravel-elixir": "^6.0.0-9",
"laravel-elixir-browsersync-official": "^1.0.0",
"laravel-elixir-vue-2": "^0.2.0",
"laravel-elixir-webpack-official": "^1.0.2",
"lodash": "^4.16.2",
"vue": "^2.0.1",
"vue-resource": "^1.0.3",
"dropzone": "^4.3.0",
"animate.css": "^3.5.0",
"node-uuid": "^1.4.7",
"json-loader": "^0.5.4"
}
}
Then tried to merge webpack config like this in gulpfile.
I tried 2 different approaches, see TRY1 and TRY2, certainly not at the same time, just posted both approaches.
const elixir = require('laravel-elixir');
require('laravel-elixir-vue-2');
// TRY 1
elixir.webpack.mergeConfig({
module: {
loaders: [{
test: /\.json$/,
loader: 'json'
}]
}
});
// TRY 2
elixir.ready(() => {
elixir.config.js.webpack = {
loaders: [{
test: /\.json$/,
loader: 'json'
}]
}
});
elixir(function (mix) {
mix.sass('app.scss');
mix.webpack('app.js');
mix.browserSync({
proxy: 'filecloud.dev'
});
mix.version(['css/app.css', 'js/app.js']);
});
But I still get the error.
Full error
If you want to use npm modules which requires the json-loader, this is the solution.
Add following to package.json file.
"json-loader": "^0.5.4"
Create webpack.config.js with the following code:
Elixir.webpack.mergeConfig({
module: {
loaders: [{
test: /\.json$/,
loader: 'json'
}]
}
});
Now you can require packages in your bootstrap.js file which require the json-loader.
Additional Notes
When you look to the index.js file where the webpack method of elixir is defined, you see that the json loader is missing inside the loaders array.
module: {
loaders: [{ test: /\.js$/, loader: 'buble', exclude: /node_modules/ }]
},

Module parse failed when using Riot with Webpack, and Babel for es2015

I have a project that is using ES2015 for the code, and also using Riot.
(The Riot components, however, do not need to be in ES2015, just old JS)
I am also using Webpack to build the project.
The problem I am getting is :
"ERROR in ./src/test-tag.tag
Module parse failed:
.../tag-loader/index.js!.../riotjs-loader/index.js?{"type":"none"}!.../test-tag.tag
Unexpected token (5:18) You may need an appropriate loader to handle
this file type."
It is complaining because of the way riot component script code looks, ie. a function must have just this for it's declaration functionName() { /* the code */ } , ie. there is no keyword function.
Here is my full project
app.js
import 'riot';
import 'test-tag.tag';
riot.mount("*");
test-tag.tag
<test-tag>
<h1>This is my test tag</h1>
<button onclick{ click_action }>Click Me</button>
<script>
//click_action() { alert('clicked!'); }
</script>
</test-tag>
index.html
<html>
<head></head>
<body>
<test-tag></test-tag>
<script src="app_bundle.js"></script>
</body>
</html>
package.json
{
"name": "riot_and_webpack",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.11.4",
"babel-loader": "^6.2.4",
"babel-preset-es2015-riot": "^1.1.0",
"riot": "^2.5.0",
"riotjs-loader": "^3.0.0",
"tag": "^0.3.0",
"tag-loader": "^0.3.0",
"webpack": "^1.13.1",
"webpack-dev-server": "^1.14.1"
}
}
webpack.config.js
var webpack = require('webpack');
const path = require('path');
const PATHS = {
src: path.join(__dirname + '/src'),
dist: path.join(__dirname + '/build'),
};
module.exports = {
entry: [path.join(PATHS.src, '/app.js')],
resolve: {
modulesDirectories: ['node_modules', '.'],
extension: [ '.js' ]
},
output: {
path: PATHS.dist,
filename: 'app_bundle.js'
},
plugins: [
new webpack.ProvidePlugin({
riot: 'riot'
})
],
module: {
preLoaders: [
{ test: /\.tag$/, exclude: /node_modules/, loader: 'riotjs-loader', query: { type: 'none' } }
],
loaders: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel',
query: {
presets: ['es2015']
}
},
{ test: /\.tag$/, loader: 'tag' },
]
}
};
Now - that will all work as expected, except that clicking the button does nothing because that code is commented out.
If the click_action line in test-tag.tag is uncommented, then $ webpack results in the error quoted at the top of this (horribly huge) question.
Is there any way I can get webpack to accept the standard riot code?
OR
Is there a different way I can define riot internal functions in a way that webpack will not complain about?
Have in mind that the "ES6 like" method syntax is something added by Riot, is not standard ES6.
This will be the standard js syntax
this.click_action = function() {
alert('clicked!')
}
And this the es6 syntax
this.click_action = () => {
alert('clicked!')
}
Also you have a typo in your button definition, it will be like this
<button onclick={click_action}>Click Me</button>

Karma/jasmine testing error: "Uncaught TypeError: Unexpected anonymous System.register call."

I am trying to get basic karma-jasmine test running but I get the following error.
Chrome 51.0.2704 (Windows 7 0.0.0) ERROR
Uncaught TypeError: Unexpected anonymous System.register call.
at D:/git/ui-components/jspm_packages/system.src.js:2891
Chrome 51.0.2704 (Windows 7 0.0.0): Executed 0 of 0 SUCCESS (0 secs / 0 secs)
Test doesn't seem to be running as well.
Folder structure is as following:
components
-[individual components]
-tests folder with simple test
-app.js(includes master component which calls all child components)
Application is working fine, but I am running into lot of problems with testing.
Any kind of help is appreciated.
Following is my package.json file
{
"name": "ui-components",
"version": "1.0.0",
"description": "POC",
"main": "index.js",
"scripts": {
"install": "jspm install && typings install",
"start": "gulp serve"
},
"repository": {
"type": "git",
"url": ""
},
"author": "",
"license": "ISC",
"devDependencies": {
"gulp": "^3.9.1",
"gulp-typescript": "^2.12.2",
"gulp-watch": "^4.3.5",
"jasmine": "^2.4.2",
"jasmine-core": "^2.4.1",
"jspm": "^0.16.30",
"karma": "^0.13.22",
"karma-chrome-launcher": "^0.2.3",
"karma-cli": "file:C:\\Users\\*********\\Downloads\\karma-cli-master",
"karma-jasmine": "^0.3.6",
"karma-jspm": "^2.0.2",
"lite-server": "^2.2.0",
"typescript": "^1.8.10",
"typings": "^1.0.4"
},
"jspm": {
"dependencies": {
"angular": "github:angular/bower-angular#^1.5.0",
"angular-route": "github:angular/bower-angular-route#^1.5.0",
"bootstrap": "github:twbs/bootstrap#^3.3.6",
"css": "github:systemjs/plugin-css#^0.1.20"
},
"devDependencies": {}
}
}
karma.config.js file
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'jspm'],
files: [
'components/**/*.js',
'components/*.js',
'components/tests/*.spec.js'
],
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
firstTest.spec.js file
import angular from 'angular';
describe("Hello World Tests", () => {
it("First", () => {
expect("TestString").toEqual("");
});
});
Index.html file
<html ng-app="app">
<head>
<script src="jspm_packages/system.js"></script>
<script src="config.js"></script>
<link rel="stylesheet" href="jspm_packages/github/twbs/bootstrap#3.3.6/css/bootstrap.css" />
<link rel="stylesheet" href="style.css" />
<script>
System.import("components/app.js");
</script>
</head>
<body>
<main-component></main-component>
</body>
</html>
app.ts file
import * as angular from 'angular'
import 'components/mainComponent/mainComponent'
angular.module("app", ['mainComponent']);
I figured out that I needed to pass in my .ts files in JSPM array object in karma.config.js file. I couldn't just pass files into following block.
files: [
'components/**/*.js',
'components/*.js',
'components/tests/*.spec.js'
]`
instead this is what it required.
jspm: {
config: "config.js",
packages: "jspm_packages/",
loadFiles: ['components/**/*spec.js'],
serveFiles: ['components/**/*.js']
},
Hopefully this helps someone else.

React startup ES2016

I'm trying to move my React code base to ES2016, but can't get pass the simplest sample, need some help here!
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<wrapper></wrapper>
<script src="js/lib/react-with-addons.min.js"></script>
<script src="js/lib/react-dom.min.js"></script>
<script src="js/bundle.js"></script>
</body>
</html>
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import { App } from './app';
ReactDOM.render(
<App/>,
document.querySelector('wrapper')
);
app.js
import React from 'react';
export default class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<app>something goes there</app>
)
}
};
gulpfile.js
var gulp = require('gulp'),
browserify = require('browserify'),
source = require('vinyl-source-stream'),
gutil = require('gulp-util'),
babelify = require('babelify');
gulp.task('jsx', function() {
browserify({
entries: './src/web/js/main.jsx',
extensions: ['.jsx'],
debug: true
})
.transform(babelify, {presets: ['es2015', 'react']})
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./dist/web/js/'))
});
gulp.task('default', ['jsx']);
and package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.html",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "?.git"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^15.0.1",
"react-dom": "^15.0.1"
},
"devDependencies": {
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babelify": "^7.2.0",
"browserify": "^13.0.0",
"gulp": "^3.9.1",
"gulp-util": "^3.0.7",
"reactify": "^1.1.1",
"vinyl-source-stream": "^1.1.0"
}
}
Seems like it should work, but I keep getting the following two errors
warning.js:44 Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).
and
invariant.js:38 Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
I know it must be something stupidly simple, but just can't figure it out. Please help.
Change this
import { App } from './app';
to:
import App from './app';