Webpack 4 and Babel 7 "import" Uncaught SyntaxError: Unexpected identifier in React - reactjs

I've been trying to set up Webpack 4 and Babel 7 to work with ES6 "import" in React. I keep getting "Uncaught SyntaxError: Unexpected identifier" at "import React from 'react';" in Chrome 71. It worked in Webpack 3 and Babel 6, so I think I'm doing something wrong with the Babel setup.
These are my dev dependencies:
"#babel/core": "^7.1.6",
"#babel/plugin-proposal-class-properties": "^7.1.0",
"#babel/plugin-proposal-decorators": "^7.1.6",
"#babel/plugin-syntax-dynamic-import": "^7.0.0",
"#babel/preset-env": "^7.1.6",
"#babel/preset-react": "^7.0.0",
"#babel/register": "^7.0.0",
"babel-loader": "^8.0.4",
"webpack": "^4.26.0",
"webpack-dev-server": "^3.1.10"
My .babelrc looks like this:
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
["#babel/plugin-proposal-decorators", { "legacy": true }],
["#babel/plugin-proposal-class-properties", { "loose": true }],
["#babel/syntax-dynamic-import"]
]
}
I've been trying babel.config.js as well, to no prevail.
My webpack-config.js file:
const HTMLWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const webpack = require('webpack');
const HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
template: __dirname + '/src/index.html',
filename: 'index.html',
injext: 'body'
})
module.exports = {
entry: ["babel-polyfill", __dirname + '/src/index.js'],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css-loader!sass-loader')
},
]
},
output: {
filename: 'transformed.js',
path: __dirname + 'build'
},
devServer: {
contentBase: './src/',
historyApiFallback: true,
hot: true,
port: 8000,
publicPath: "/src/public",
noInfo: false
},
plugins: [
HTMLWebpackPluginConfig,
new ExtractTextPlugin('public/css/style.css', {
allChunks: true
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production')
}),
]}

Okay, i seemed to have fixed to issue after spitting through my webpack config. The issue was caused by this:
devServer: {
contentBase: './src/',
historyApiFallback: true,
hot: true,
port: 8000,
publicPath: "/src/public",
noInfo: false
},
I'll see if i can find what exactly causes Webpack not to bundle with this. Thanks for all the help anyway!

Related

webpack bundle file is not being generated with no errors

I am new to react, trying to learn webpack configuration. I am using webpack4 for my project, however, after setting up webpack, the bundle files are not generated, neither the js file nor the html file and there is no error.
The output on the console says "compiled successfully". How do i fix this. I have been struggling for about a week and no online resource seems to give me what i want.
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const port = process.env.PORT || 3000;
const paths = {
DIST: path.resolve(__dirname, 'dist'),
SRC: path.resolve(__dirname, 'src'),
JS: path.resolve(__dirname, 'src/js')
}
const htmlPlugin = new HtmlWebpackPlugin({
template: "./src/index.html",
filename: "./index.html"
});
module.exports = {
mode: 'development',
entry: path.join(paths.JS, 'index.js'),
output: {
path: paths.DIST,
filename: 'app.bundle.js'
},
module:{
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader",
options:{
modules: true,
importLoaders: 1,
localIndentName: "[name]_[local]_[hash:base64]",
sourceMap: true,
minimize: true,
camelCase:true
}
}
]
}
]
},
plugins: [htmlPlugin],
devServer: {
publicPath: paths.DIST,
host: 'localhost',
port: port,
historyApiFallback: true,
open:true,
hot: true
}
};
Make sure all path correctly, not have missing file.
src/js/index.js
src/index.html
make sure run webpack correctly to show log like:
package.json
"scripts": {
"start": "webpack --config webpack.config.js --bail --progress --profile"
},
and run by npm start, then will show the log.
if you want, you can use new babel version. change your bable with this:
"dependencies": {
"#babel/core": "^7.0.0-beta.42",
"#babel/preset-env": "^7.0.0-beta.42",
"babel-eslint": "^8.0.3",
"babel-loader": "^8.0.0-beta.0",
"css-loader": "^0.28.11",
"html-webpack-plugin": "^3.1.0",
...
"style-loader": "^0.20.3",
"webpack": "^4.4.1",
"webpack-cli": "^2.0.13"
},
.babelrc
{
"presets": ["#babel/preset-env"],
"plugins": ["#babel/plugin-proposal-object-rest-spread"]
}
then update your webpack rule:
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: [require('#babel/plugin-proposal-object-rest-spread')]
}
},
exclude: /node_modules/
},

Webpack3 unable to parse JSX files

I have the following configuration for a react based application that is failing JSX parsing during webpack build:
ERROR in ./src/App.jsx
Module parse failed: /Users/sangupta/git/plx/ui2/src/App.jsx Unexpected token (9:15)
You may need an appropriate loader to handle this file type.
|
| render() {
| return <div class='hello'>Hello World</div>;
| }
|
# multi (webpack)-dev-server/client?http://localhost:9000 webpack/hot/dev-server src/App.jsx
Any suggestions on what might be wrong?
The following is the package.json file:
{
"name": "Test-Project",
"version": "0.1.0",
"private": true,
"devDependencies": {
"autoprefixer": "6.4.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"babel-preset-stage-1": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "0.28.4",
"file-loader": "0.9.0",
"html-webpack-plugin": "2.30.1",
"less": "2.7.1",
"less-loader": "2.2.3",
"postcss-loader": "2.0.5",
"style-loader": "0.13.2",
"webpack": "3.4.1",
"webpack-dev-server": "2.6.1"
},
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
"scripts": {
"build": "webpack",
"build-production": "NODE_ENV=production npm run build",
"watch": "webpack-dev-server --hot --progress"
}
}
The following is webpack.config.json file:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const isProduction = process.env.NODE_ENV === 'production';
module.exports = {
context: __dirname,
entry: {
app: 'src/App.jsx',
vendor: [ "react", "react-dom" ]
},
devServer: {
contentBase: path.join(__dirname, 'assets'),
compress: true,
port: 9000,
hot: true,
https: false,
noInfo: false,
historyApiFallback: true
},
resolve: {
extensions: [ '.js', '.jsx' ],
alias: {
src: './src'
},
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: [
path.resolve(__dirname, "src")
],
exclude: /node_modules/,
loader: [
'babel-loader',
],
options: {
presets: [ "es2015" ]
}
},
{
test: /\.(jpe?g|gif|png|svg|woff|ttf|wav|mp3|css)$/,
use: [
"file-loader"
]
}
]
},
output: {
path: path.join(__dirname, 'build'),
filename: '[name].js'
},
devtool: isProduction ? 'source-map' : 'cheap-module-eval-source-map',
module: {
rules: []
},
// Tell webpack to use html plugin
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
new webpack.ProvidePlugin({
'React': 'react',
}),
new UglifyJsPlugin({ sourceMap: !isProduction }),
new HtmlWebpackPlugin({ title: 'MultiPLX', template: 'src/index.ejs', inject : 'body' })
]
};
You should be using the react babel preset:
npm install --save-dev babel-preset-react
webpack.config.js
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: [
path.resolve(__dirname, "src")
],
exclude: /node_modules/,
loader: [
'babel-loader',
],
options: {
presets: [ "react", "es2015" ]
}
},
{
test: /\.(jpe?g|gif|png|svg|woff|ttf|wav|mp3|css)$/,
use: [
"file-loader"
]
}
]
},

why babel loader and jsx loader is not working in webpack version 3.x in react app

Package.json this is my package json file.
I have already install npm install --save-dev babel-loader babel-core in my app
/* Package.json*/
{
"name": "tripdetail",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"dev": "webpack-dev-server",
"prod": "webpack -p"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel": "^6.23.0",
"babel-cli": "^6.24.1",
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-env": "^1.6.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.4",
"extract-text-webpack-plugin": "^3.0.0",
"html-webpack-plugin": "^2.30.1",
"node-sass": "^4.5.3",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"sass-loader": "^6.0.6",
"style-loader": "^0.18.2",
"webpack": "^3.5.4",
"webpack-dev-server": "^2.7.1"
},
"dependencies": {
"eslint": "^4.4.1"
},
"description": ""
}
.babelrc this is my babelrc file. I have also configured it by this code -
/*.babelrc */
{
"presets": ["es2015", "es2016", "react"]
}
webpack.config.js this is my webpack config js file. I have also configure module and tested but it is not working.
/webconfig.js code/
'use strict';
var HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
var path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.bundle.js'
},
module: {
rules: [{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ["css-loader", "sass-loader"],
publicPath: '/dist',
},
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['react', 'es2015']
}
}
)
}]
},
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000,
stats: 'errors-only',
open: true
},
plugins: [new HtmlWebpackPlugin({
title: 'tripDetailPage',
hash: true,
minify: {
collapseWhitespace: false
},
template: './src/index.html'
}), new ExtractTextPlugin({
filename: "tripDetail.css",
disable: false,
allChunks: true
})]
}
app.js
const css = require('./app.scss');
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<div>Hello</div>,
//e('div', null, 'Hello Worlddddd'),
document.getElementById('root')
);
Compiletion ERROR
ERROR in ./src/app.js
Module parse failed: E:\trip-react\src\app.js Unexpected token (10:3)
You may need an appropriate loader to handle this file type.
|
| ReactDOM.render(
| <div>Hello</div>,
| //e('div', null, 'Hello Worlddddd'),
| document.getElementById('root')
# multi (webpack)-dev-server/client?http://localhost:9000 ./src/app.js
webpack: Failed to compile.
ERROR in ./src/app.js
Have you tried renaming that file to /src/app.jsx ?
Check out resolve.extensions and module.loaders, in your webpack.config.js file -- both should refer to .jsx files.
This error is related to webpack.config.js. Rules was wrongly putted in this file. Here is my correct webconfig.
'use strict';
var HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
var CleanWebpackPlugin = require('clean-webpack-plugin');
var path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.bundle.js'
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ["css-loader", "sass-loader"],
publicPath: '/dist',
})
},
{
test:/\.js$/,
use:'babel-loader',
exclude:/node_modules/
},
{
test:/\.jsx$/,
use:'babel-loader',
exclude:/node_modules/
}
]
},
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000,
stats: 'errors-only',
open: true
},
plugins: [new HtmlWebpackPlugin({
title: 'tripDetailPage',
hash: true,
minify: {
collapseWhitespace: false
},
template: './src/index.html'
}), new ExtractTextPlugin({
filename: "tripDetail.css",
disable: false,
allChunks: true
}),]
}

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

Resources