Webpack 4 Babel and React error in handling the JSX files - reactjs

I keep getting this error, I tried several solutions using the search on this website and github but I cannot figure out what is wrong with it.
Here is what I have in my package.json
"dependencies": {
"react": "^16.4.2",
"react-dom": "^16.4.2"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.16.5",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
}
Here is my webpack config
module.export = {
entry: './src/index.js',
output: {
path: path.join(__dirname, '/dist'),
filename: 'main.js'
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
module: {
rules: [
{
test: /\.jsx$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
}
I created a .babelrc with this
{
"presets": ["env", "react", "es2015"]
}
Then I run
webpack-dev-server --mode development --hot
But if fails on this
ReactDOM.render(<App />, document.getElementById('app'));
This is the error I get in the console
ERROR in ./src/index.js 5:16
Module parse failed: Unexpected token (5:16)
You may need an appropriate loader to handle this file type.
| import App from './components/App';
|
> ReactDOM.render(<App />, document.getElementById('app'));
# multi (webpack)-dev-server/client?http://localhost:8080
(webpack)/hot/dev-server.js ./src main[2]
I spent 3 hours on google, stackoverflow and github but I cannot figure out what is wrong with this. Any help is highly appreciated.
Thanks!

Just throwing it there but you have
module.export
while it should be
module.exports

The issue is your config handles only files with .jsx but you also have .js file so, Change regex in webpack config and recompile your app
const path = require("path");
module.export = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.js',
publicPath: "/
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
resolve: {
modules : [
path.resolve("./src"),
path.resolve("./node_modules")
],
extensions: ['*', '.js', '.jsx']
}
}
replace your exiting modules with these dependencies
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"webpack": "^4.16.5",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
.babelrc
{
"presets": [
["env", {
"targets": {
"browsers": ["last 2 versions", "safari >= 7"]
}
}],
"react"
],
"plugins": [
"transform-class-properties",
"transform-object-rest-spread"
]
}

Related

ReactJS - Unexpected Token with 3 comma

Im tring to compile my react frontend app but I got a couple of error about "..." syntax:
ERROR in condition.jsx
Module build failed: SyntaxError: Unexpected token (25:10)
23 | show_table : undefined,
24 | fa_count : 0,
> 25 | ...this.state
| ^
26 | }
condition.jsx extends (with OOP) another component so I need ...this.state to merge parent state with the local state.
When launcing it with npm start, it works perfectly but the compiler seems doesn't want that syntax.
UPDATED:
This is my current webpack settings:
const webpack = require('webpack');
const path = require('path');
const Uglify = require("uglifyjs-webpack-plugin");
var plugins = [];
plugins.push(new Uglify());
var config = {
context: __dirname + '/src',
entry: {
javascript: "./index.js",
},
plugins: plugins,
output: {
path: path.join(__dirname,'../static/js/'),
filename: 'bundle.js',
},
devServer: {
inline: true,
port: 8080
},
resolveLoader: {
modules: [path.join(__dirname, 'node_modules')]
},
module: {
loaders: [
{
test:/\.(js|jsx)?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['env','react']
}
},
{
test: /\.css$/,
loader: 'style-loader'
},
{
test: /\.css$/,
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
},
{
test: /\.svg$/,
use: [
{
loader: "babel-loader"
},
{
loader: "react-svg-loader",
options: {
jsx: true // true outputs JSX tags
}
}
]
}
]
},
}
module.exports = env => {
return config;
}
Lanching with this command:
./node_modules/.bin/webpack --config webpack.config.js
In a comment, you said that you don't have any babelrc. Then I already re-read the Webpack offical document and take this sample code from there for you:
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: [require('#babel/plugin-proposal-object-rest-spread')]
}
}
}
]
after installing the babel-plugin-transform-object-rest-spread package, you could follow this sample code to update your webpack config. Read more about it: Webpack Loader
This is the combination that works for me, I'm using the babel-preset-stage-2 instead.
In the webpack.config.js:
....
module: {
rules: [
{
test:/\.(js|jsx)?$/,
use: ['babel-loader']
},
....
]
}
....
I create a .babelrc file in the root folder and its content is:
{
"presets": ["env", "react", "stage-2"],
....
}
And this is my package.json file:
{
"name": "demo",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --open"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"clean-webpack-plugin": "^0.1.19",
"css-loader": "^0.28.11",
"html-webpack-plugin": "^3.2.0",
"node-sass": "^4.9.0",
"react-hot-loader": "^4.3.3",
"sass-loader": "^7.0.3",
"style-loader": "^0.21.0",
"webpack": "^4.15.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
},
"dependencies": {
"prop-types": "^15.6.2",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-redux": "^5.0.7",
"redux": "^4.0.0",
"uuid": "^3.3.2"
}
}
Hopefully, it works for you.
You didn't tell about your configuration. But I assume babel and webpack. This seems to be an issue with your babel config. Try this plugin:
https://www.npmjs.com/package/babel-plugin-transform-object-rest-spread
After you've installed it, add
"plugins": ["transform-object-rest-spread"]
To your .babelrc file and run the webpack again.

Cant Import CSS files into React Project

when i tried to import css file it showed error that loaders are missing. so i have installed css-loader and style-loader packages. if i add those packages to webpack.config.js i get following error. i dont know how to resolve it.
ERROR in ./node_modules/css-loader!./src/index.js
Module build failed: Unknown word (1:1)
> 1 | import React from 'react';
| ^
2 | import ReactDOM from 'react-dom';
3 | import {App} from './components/App';
4 |
# ./src/index.js 3:14-73
# multi (webpack)-dev-server/client?http://localhost:8080
./src/index.js
Webpack.config.js
module.exports = {
entry: [
'./src/index.js'
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader","style-loader","css-loader"],
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './dist'
}
};
i have installed following dependecies
package.json
{
"name": "Reactjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --config ./webpack.config.js --mode
development"
},
"keywords": [],
"author": "",
"license": "ISC",
"babel": {
"presets": [
"env",
"react",
"stage-2"
]
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "^0.28.11",
"style-loader": "^0.20.3",
"webpack": "^4.2.0",
"webpack-cli": "^2.0.12",
"webpack-dev-server": "^3.1.1"
},
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-router-dom": "^4.2.2"
}
}
Modifie your webpack.config.js to this and import your css file on your App component like this import './file.css'; (assuming that the css file is in the same directory as your App component)
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './dist'
}
};
You need to add a separate rule for css to your webpack.config in order to load css into your project.
...
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"]
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
...
You're using style-loader and css-loader to transform your .jsx files which is going to throw an error.

React Jest - Unexpected token import

I'm learning react and I want to test one of my components but I'm stuck with this error:
{import React from 'react';
^^^^^^
SyntaxError: Unexpected token import
Here's some things I have tried from reading post on stackoverflow and github
added test presets and these plugins "transform-es2015-modules-commonjs", dynamic-import-node" to my babel config
{
"presets": ["es2015", "react"],
"env": {
"test": {
"presets":[
["es2015", { "modules": false }],
"stage-0",
"react"],
"plugins": [
"transform-es2015-modules-commonjs",
"dynamic-import-node"
]
}
}
}
In my package.json the Jest property has these settings:
"jest": {
"verbose": true,
"moduleFileExtensions": [
"ts",
"tsx",
"jsx",
"js"
],
"transform": {},
"moduleDirectories": [
"node_modules"
],
"transformIgnorePatterns": [
"node_modules/(?!react)/"
],
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$"
},
My actual component is built with ES6 and typescript if that helps you help me :)
From what I have read, it seems jest chokes on import because node doesn't understand ES6 import. None of the solutions I have tried online have seemed to work.
Also here are my dev Dependencies:
"devDependencies": {
"awesome-typescript-loader": "^3.2.2",
"babel-cli": "^6.24.1",
"babel-core": "^6.25.0",
"babel-eslint": "^7.2.3",
"babel-jest": "^20.0.3",
"babel-loader": "^7.1.1",
"babel-plugin-dynamic-import-node": "^1.0.2",
"babel-plugin-transform-es2015-modules-commonjs": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"css-loader": "^0.28.4",
"enzyme": "^2.9.1",
"eslint": "^4.4.1",
"eslint-config-airbnb": "^15.1.0",
"eslint-loader": "^1.9.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-jsx-a11y": "^6.0.2",
"eslint-plugin-react": "^7.2.0",
"extract-text-webpack-plugin": "^3.0.0",
"html-webpack-harddisk-plugin": "^0.1.0",
"html-webpack-plugin": "^2.30.1",
"jest": "^20.0.4",
"node-sass": "^4.5.3",
"react-test-renderer": "^15.6.1",
"regenerator-runtime": "^0.10.5",
"sass-loader": "^6.0.6",
"source-map-loader": "^0.2.1",
"style-loader": "^0.18.2",
"ts-jest": "^20.0.10",
"typescript": "^2.4.2",
"webpack": "^3.5.1",
"webpack-dev-middleware": "^1.12.0",
"webpack-dev-server": "^2.7.0"
},
Webpack config
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
const HOST = "127.0.0.1";
const PORT = "9000";
const devServerUrl = "http://localhost:" + PORT + "/";
const config = {
devtool: 'source-map',
context: __dirname, // `__dirname` is root of project and `src` is source
entry:
[
'./src/index.js',
'./src/ui/styles.scss'
],
output: {
path: path.join(__dirname, 'dist'),
filename: "bundle.js",
publicPath: ''
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx', '.scss', '.css']
},
module: {
rules: [
{ test: /\.tsx?$/, loader: "awesome-typescript-loader" },
{ test: /\.js$/, exclude: /node_modules/, loader: ['babel-loader', 'eslint-loader'] },
{ test: /\.jsx$/, exclude: /node_modules/, loader: ['babel-loader', 'eslint-loader'] },
{
test: /\.(sass|scss)$/, use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
}
]
},
devServer: {
contentBase: "dist/",
noInfo: true,
inline: true,
compress: true,
port: PORT,
host: HOST,
hot: true
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html', // Output file name.
template: './public/index.html', // Use our HTML file as a template for the new one.
inject: 'body',
alwaysWriteToDisk: true,
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
}),
new ExtractTextPlugin({ // define where to save the file
filename: 'styles.bundle.css'}),
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackHarddiskPlugin({
outputPath: path.resolve(__dirname, 'dist')
})
],
};
module.exports = config;
Thanks
Jest doesn't work with Typescript.
I have removed Jest from my project and installed Mocha, Karma, Chai & Enzyme.
Effortless to set up compared to Jest which masquerades as a:
Zero configuration testing platform
This article was a huge help: Getting Started on Testing with Typescript, ReactJS, and Webpack.
Hopefully this will save others from wasting their time getting Jest to work with Typescript.
It's because you have configured babel to not transpile ES6 modules
"presets":[
["es2015", { "modules": false }],
Try again with that modules to true (or omitted, since it defaults to true) and it should work.
you need to install babel to compile your es6 and react code
do it using
C:\Users\username\Desktop\reactApp>npm install babel-core
C:\Users\username\Desktop\reactApp>npm install babel-loader
C:\Users\username\Desktop\reactApp>npm install babel-preset-react
C:\Users\username\Desktop\reactApp>npm install babel-preset-es2015
Try to keep our webpack as
var config = {
entry: './todoApp.js',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 9191
},
module: {
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
],
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;

Having an issue when configuring HotModuleReplacement in webpack 2

I'm trying to integrate HotModuleReplacement and following this boilerplate, but is not working with my webpack configuration.
The "issue" I am having is in the output.publicPath entry. Following the example I mentioned, that line is "necessary for HMR to know where to load the hot update chunks", but when I include it in my webpack config it gives me this error GET http://localhost:3000/ 404 (Not Found). If I don't include it, webpack compiles everything successfully, but HMR does not work even though when I look at the console I get this
[WDS] App hot update...
dev-server.js:45 [HMR] Checking for updates on the server...
log-apply-result.js:20 [HMR] Updated modules:
log-apply-result.js:22 [HMR] - ./src/components/App.js
dev-server.js:27 [HMR] App is up to date.
Below is webpack.config.js file.
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/index.js'
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/static/'
},
devtool: 'inline-source-map',
module: {
rules: [
{ test: /\.(js)$/, exclude: /node_modules/, use: ['react-hot-loader/webpack', 'babel-loader'] },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ] },
{ test: /\.(png|jpg)$/, loader: 'file-loader?name=images/[name].[hash].[ext]' },
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=fonts/[name].[hash].[ext]&mimetype=application/font-woff'},
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,loader: 'file-loader?name=fonts/[name].[hash].[ext]&mimetype=application/font-woff'},
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=fonts/[name].[hash].[ext]&mimetype=application/octet-stream'},
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=fonts/[name].[hash].[ext]'},
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=images/[name].[hash].[ext]&mimetype=image/svg+xml' }
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new HtmlWebpackPlugin({ template: 'public/index.html', favicon: 'public/favicon.ico' })
],
devServer: {
host: 'localhost',
port: 3000,
historyApiFallback: true,
hot: true
}
}
What am I missing?
These are my project dependencies just in case
"dependencies": {
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-prop-types": "^0.4.0",
"semantic-ui-css": "^2.2.10",
"semantic-ui-react": "^0.68.3"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-env": "^1.4.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-1": "^6.24.1",
"css-loader": "^0.28.1",
"file-loader": "^0.11.1",
"html-webpack-plugin": "^2.28.0",
"react-hot-loader": "next",
"style-loader": "^0.17.0",
"webpack": "^2.5.1",
"webpack-dev-server": "^2.4.5"
}
EDIT
I got it working. I changed publicPath to publicPath: '/' and added {"modules": false} to my .babelrc file
Below is my .babelrc file
{
"presets": [["env",{"modules": false}], "react", "stage-1"]
}
I guess I have a new question, what does {"modules": false} mean? what it is used for?
.babelrc is the configuration for the babel transpiler.
"Setting this to false will not transform modules.".
source: https://babeljs.io/docs/plugins/preset-es2015/#options

Webpack React build throwing errors on html tags

I am getting an error every time I run npm start, here is my error....
ERROR in ./app/App.js
Module build failed: SyntaxError: Unexpected token (8:3)
6 | render() {
7 | return (
> 8 | <div>
| ^
9 | Testing this
10 | </div>
11 | )
This is inside a simple react component. For some reason html tags are causing errors in my build. Below is my webpack.config.js and package json file.
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: [
'./app/App.js'
],
output: {
path: __dirname + '/public',
filename: "bundle.js"
},
plugins: [HTMLWebpackPluginConfig],
devServer: {
inline:true,
contentBase: './public',
port: 3333
},
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.scss$/,
loader: 'style!css!sass'
}]
}
};
the package json
{
"name": "lr",
"version": "1.0.0",
"description": "",
"main": "App.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "sam",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.21.0",
"babel-loader": "^6.2.10",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"css-loader": "^0.26.1",
"html-webpack-plugin": "^2.25.0",
"sass": "^0.5.0",
"sass-loader": "^4.1.1",
"style-loader": "^0.13.1",
"webpack": "^1.14.0",
"webpack-dev-server": "^1.16.2"
},
"dependencies": {
"react": "^15.4.1",
"react-dom": "^15.4.1",
"react-hot-loader": "^1.3.1",
"react-router": "^3.0.0"
}
}
No clue why html tags are throwing errors.
You'll need to inform webpack that you also want it to consume .jsx extensions. Try updating your test pattern:
{
test : /\.(js|jsx)$/,
loaders: ['babel'],
include: path.join(__dirname, 'src')
}
You also need a .babelrc file to then inform babel how you'd like it to perform the compilation:
{
"presets": ["es2015", "react"]
}
Have a peek here for a working implementation: https://github.com/mikechabot/react-boilerplate

Resources