Not able to transpile jsx to js using babel - javascript

I am learning react and here is my simple project sturcture:
my_project
--node_modules
--index.js
--index.html
--package.json
--.babelrc
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="root"></div>
<script src="index.js"></script>
</body>
</html>
index.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
package.json
{
"name": "my_project",
"version": "1.0.0",
"description": "frontend using react js",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "babel src -d dist"
},
"scripts": {
"build": "babel --presets es2015 -d dist"
},
"author": "kishan",
"license": "ISC",
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2"
},
"devDependencies": {
"babel-cli": "^6.23.0",
"babel-core": "^6.23.1",
"babel-loader": "^6.4.0",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.23.0",
"webpack": "^2.2.1"
},
"babel": {
"plugins": ["transform-react-jsx"],
"ignore": [
"foo.js",
"bar/**/*.js"
]
}
}
webpack.config.js
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
config = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./index.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
module.exports = config;
I am getting following error in console in browser for index.js line 1:
Uncaught SyntaxError: Unexpected token import
Please help me what is wrong with this code?

You forgot to define the babel-loader in webpack file, put this part:
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
Use this webpack file:
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var config = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./index.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
}
module.exports = config;
Update:
From Webpack Doc:
When using watch mode, webpack installs file watchers to all files,
which were used in the compilation process. If any change is detected,
it’ll run the compilation again. When caching is enabled, webpack
keeps each module in memory and will reuse it if it isn’t changed.

Add babel-loader in webpack to transpile jsx or js
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
config = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./index.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
module.exports = config;
Starting the webpack in watch mode and will not require you to build again to do that add the followign in your package.json
"scripts": {
"build": "webpack --progress --color --config webpack.config.js --watch",
}
You may also use webpack-dev-server in hot-loading mode

Related

Debugging Javascript in VS Code - unbound breakpoints

I have some issues with unbound breakpoints in VS Code. My project structure is as follows:
mittfast2 - Project root
|_webapp
|_.vscode
|_launch.json
|_src
|_java
|_resources
|_webapp - React components etc.
|_index.js
|_node_modules
|_package.json
My package.json has the following scripts:
"scripts": {
"start": "webpack serve --mode development",
"deploy": "NODE_ENV=production webpack -p --config webpack.production.config.js",
"build": "webpack --mode production",
"test": "jest",
"test:coverage": "jest --coverage",
"test:watch": "jest --watch --coverage"
}
I run with "npm start" and visit http://localhost:3000. Inspecting the sources gives me this:
I can successfully use the built in debugger in Chrome by adding and hitting breakpoints.
But when I add breakpoints in IntelliJ and run my debug launcher, they are all "Unbound breakpoint". This is my launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "WSL Chrome",
"type": "pwa-chrome",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}/src",
"sourceMapPathOverrides": {
"webpack:///./src/*": "${webRoot}/*",
"webpack:///src/*": "${webRoot}/*"
}
}
]
}
I believe something is wrong with my launch.json, specifically when I map my sources.
This is my webpack.config.js in case it is of interest:
const path = require('path')
/* Utilities */
const webpackHtml = require('html-webpack-plugin')
const webpackBundleAnalyzer = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
entry: ['./src/main/webapp/index'],
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
'babel-loader',
'eslint-loader',
]
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader'
}
]
},
{
test: /\.(s*)css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
{
test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]?[hash:8]',
}
}
]
},
plugins: [
new webpackHtml({
hash: true,
template: './src/main/webapp/index.html',
filename: 'index.html'
}),
new webpackBundleAnalyzer({
openAnalyzer: false
}),
new MiniCssExtractPlugin({
filename: 'style.css'
})
],
devServer: {
port: 3000,
hot: true,
historyApiFallback: true,
proxy: {
'/resources/*': {
target: 'http://localhost:8080/fenix/',
secure: false,
onError: error => { console.log('::PROXY ERROR::', error) }
}
}
},
resolve: {
alias: {
'#actions': path.resolve(__dirname, 'src/main/webapp/actions'),
'#components': path.resolve(__dirname, 'src/main/webapp/components'),
'#gui': path.resolve(__dirname, 'src/main/webapp/gui'),
'#functions': path.resolve(__dirname, 'src/main/webapp/functions'),
'#middleware': path.resolve(__dirname, 'src/main/webapp/middleware'),
'#reducers': path.resolve(__dirname, 'src/main/webapp/reducers'),
'#styles': path.resolve(__dirname, 'src/main/webapp/styles'),
}
}
}
Given my project structure, can anyone see why my launch.json is incorrect and suggest improvements to successfully bind the breakpoints?
I hope this question contains all the information needed. Otherwise, please suggest improvements and I will happily edit the question.
Thanks!

ReactDOM.render not accepting JSX

I cannot get ReactDOM.render(...) to accept any JSX tag, however if I use React.createElement(...) it works.
This is my index.jsx file:
import React from "react";
import ReactDOM from "react-dom";
// THIS WORKS!
//var elem = React.createElement('h1',{},"Hello");
//ReactDOM.render(elem, document.getElementById("content"));
// THIS DOESN'T WORK!
ReactDOM.render(<h1>Hello World!</h1>, document.getElementById("content"));
In the index.html file there is a div with id="content" somewhere.
This is my package.json file:
{
"name": "static",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack -p --progress --config webpack.config.js",
"dev-build": "webpack --progress -d --config webpack.config.js",
"watch": "webpack --progress -d --config webpack.config.js --watch"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/preset-env": "^7.4.5",
"#babel/preset-react": "^7.0.0",
"webpack": "^4.35.0",
"webpack-cli": "^3.3.5"
},
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
This is my webpack.config.js file:
const webpack = require('webpack');
const config = {
entry: __dirname + '/js/index.jsx',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
};
module.exports = config;
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
The error I am getting is:
ERROR in ./js/index.jsx 11:16
Module parse failed: Unexpected token (11:16)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
|
> ReactDOM.render(<h1>Hello World!</h1>, document.getElementById("content"));
|
==============================================
Solution:
1st of all the webpack.config.js was wrong (see accepted answer).
After, I had to install babel-loader with npm install -D babel-loader #babel/core #babel/preset-env webpack and then created .babelrc file at the same path of the other config. files, with the content:
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
You are placing the rules in the wrong place.
the correct config is:
const webpack = require('webpack');
const config = {
entry: __dirname + '/js/index.jsx',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
};
module.exports = config;

Style loader not loading css in my <head>

I am trying to import my css in my webpack bundle.
We are creating an angular 1 application and we are bundle it with webpack. For the moment everything was fine. The html has the bunlde and vendor scripts. Other js are been in included and the views are copied and included.
In this step we are trying to include a css file we create in a styles/ folder. For the output I guess that the css file is processed by css-loader, but the style-loader didn't include the css file in the tag.
Can anyone give me a hint?
My webpack.config in the rules is like this.
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require ('webpack'); module.exports = {
mode: 'development',
entry: {
vendor: ['angular', '#uirouter/angularjs'],
app: './src/index.js'
},
devtool: 'inline-source-map',
devServer: {
contentBase: 'dist',
hot: true,
inline: true,
open:'chrome',
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Output Management',
template: './src/index.html',
}),
new webpack.HotModuleReplacementPlugin(),
new CopyWebpackPlugin([
{
from: './src/views/**/*',
to: ''
},
], {
ignore: [],
copyUnmodified: true
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.html$/,
use: {
loader: 'html-loader',
options: {
attrs:[
':data-src'
]
}
}
}
]
}
};
My index.html is
<!doctype html>
<html>
<head>
<title>Getting Started</title>
</head>
<body>
<a ui-sref="about" ui-sref-active="active">About</a>
<ui-view></ui-view>
</body>
</html>
My index.js is like this:
import first_controller from './controllers/first_controller.js';
import uiRouter from '#uirouter/angularjs';
//import css from './styles/main.css'; // I try this also
import './styles/main.css'; //This isn't working either.
var app = angular.module ('app', ['ui.router']);
app.controller ('first_controller', first_controler);
app.config(function($stateProvider) {
var exampleState = {
name: 'example',
url: '/example',
templateUrl: './src/views/example.html', }
$stateProvider.state(exampleState );
});
my css in the folder /styles/main
.example_css {
color: red;
}
And the example view is:
<div class="example_css">Example</div>
My package.json is:
{
"name": "Example",
"version": "1.0.0",
"main": "webpack.config.js",
"scripts": {
"build": "webpack --colors",
"start": "webpack-dev-server --progress --colors --watch --inline --open"
},
"devDependencies": {
"angular": "^1.7.7",
"clean-webpack-plugin": "^2.0.0",
"copy-webpack-plugin": "^5.0.0",
"css-loader": "^2.1.1",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^0.23.1",
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3",
"webpack-dev-server": "^3.2.1"
},
"dependencies": {
"#uirouter/angularjs": "^1.0.22"
}
}
Depending on your webpack version you want to use extract-text-webpack-plugin or mini-css-extract-plugin to put styles into a file.
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
},
plugins: [
new ExtractTextPlugin("styles.css"),
]
}
To include a path to CSS file in index.html on build - see how to create templates with HtmlWebpackPlugin.

Webpack + React16 + Javascript ES6 "Unexpected token" error

I know this question was asked about thousand times, but I didn't find any solution that works. I'm still getting the same error. Here are my config files:
package.json:
{
"scripts": {
"start": "webpack-dev-server",
"build": "webpack"
},
"dependencies": {
"jquery": "^3.2.1",
"react": "^16.1.1",
"react-dom": "^16.1.1"
},
"devDependencies": {
"babel": "^6.23.0",
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"clean-webpack-plugin": "^0.1.17",
"css-loader": "^0.28.7",
"html-webpack-plugin": "^2.30.1",
"style-loader": "^0.19.0",
"webpack": "^3.8.1",
"webpack-dev-server": "^2.9.4"
}
}
webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: './src/app/app.jsx',
devtool: 'source-map',
devServer: {
contentBase: path.join(__dirname, "dist"),
hot: true
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
],
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: "babel-loader",
query:
{
presets: ['es2015', 'react']
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/app/index.html'
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.bundle.js'
}
};
app.jsx:
import React from "react"
React.render(<h1>hello world</h1>, document.getElementById("root-component"));
Webpack throws the following error:
ERROR in ./src/app/app.jsx
Module parse failed: Unexpected token (3:13)
You may need an appropriate loader to handle this file type.
| import React from "react"
|
| React.render(<h1>hello world</h1>, document.getElementById("root-component"));
I tried multiple solutions (like adding .babelrc file with presets), nothing works. Any help?
Your webpack.config.js is incorrect as per webpack v3.
You need to add another entry into the rules array just like you are doing for loading CSS.
Moreover query should be renamed options.
See Webpack Documentation for more info on migrating from v2 to v3
The fixed webpack.config.js is as follows:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: './src/app/app.jsx',
devtool: 'source-map',
devServer: {
contentBase: path.join(__dirname, "dist"),
hot: true
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
options: {
presets: ['es2015', 'react']
}
}
]
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
],
}
],
},
plugins: [
new HtmlWebpackPlugin({
template: './src/app/index.html'
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.bundle.js'
}
};
Before:
ERROR in ./src/app/app.jsx
Module parse failed: Unexpected token (3:13)
Ater (bundle correctly created):
app.bundle.js 424 kB 0 [emitted] [big] main
app.bundle.js.map 499 kB 0 [emitted] main

Webpack - Getting node modules Into Bundle and loading into html file

I am trying to use node_modules in the browser via WebPack. I've read the tutorial and beginning steps but am stuck.
I have used webpack to generate bundle.js with the webpack config below and upon going to my index.html in Chrome browser I get the error:
Uncaught ReferenceError: require is not defined
at Object.<anonymous> (bundle.js:205)
What additional steps do I have to do to get the browser to recongnize require?
index.html
<script src="bundle.js"></script>
<button onclick="EntryPoint.check()">Check</button>
index.js
const SpellChecker = require('spellchecker');
module.exports = {
check: function() {
alert(SpellChecker.isMisspelled('keng'));
}
};
package.json
{
"name": "browser-spelling",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"node-loader": "^0.6.0",
"spellchecker": "^3.3.1",
"webpack": "^2.2.1"
}
}
webpack.config.js
module.exports = {
entry: './index.js',
target: 'node',
output: {
path: './',
filename: 'bundle.js',
libraryTarget: 'var',
library: 'EntryPoint'
},
module: {
loaders: [
{
test: /\.node$/,
loader: 'node-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}
]
}
};
In your webpack.config.js you specified that you want to build this bundle for Node.js:
target: 'node',
And webpack decided to keep require calls, because Node.js supports them. If you want to run it in a browser, you should use target: 'web' instead.
In the new "webpack": "^5.75.0", Required has been changed to rules
webpack.config.js
const path = require("path");
var webpack = require("webpack");
module.exports = {
entry: "./index.js",
target: "node",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
},
module: {
rules: [
{
test: /\.node$/,
use: "node-loader",
},
{
test: /\.js$/,
exclude: /node_modules/,
},
],
},
};
package.json
{
"name": "arrybsc",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bootstrap": "^5.2.3",
"lodash": "^4.17.21"
},
"devDependencies": {
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1"
}
}

Categories