Webpack and React -- Unexpected token - javascript

I am new to React and Webpack. I am setting up my first project, when I try to run the webpack-dev-server my code does not compile!
Update
Answer below is correct. I needed to add 'react' to babel loader presets. You can see the full source for project here: https://github.com/cleechtech/redux-todo
Error:
$ webpack-dev-server
http://localhost:8080/webpack-dev-server/
webpack result is served from /
content is served from ./dist
Hash: d437a155a1da4cdfeeeb
Version: webpack 1.12.14
Time: 5938ms
Asset Size Chunks Chunk Names
bundle.js 1.51 kB 0 [emitted] main
chunk {0} bundle.js (main) 28 bytes [rendered]
[0] multi main 28 bytes {0} [built] [1 error]
ERROR in ./src/index.js
Module build failed: SyntaxError: /Users/connorleech/Projects/redux-todo/src/index.js: Unexpected token (7:16)
console.log(ReactDOM);
ReactDOM.render(<App />,document.getElementById('root'));
src/index.js:
var react = require('react');
var ReactDOM = require('react-dom');
var App = require('./components/App');
console.log(ReactDOM);
ReactDOM.render(<App />,document.getElementById('root'));
src/components/App.js
var React = require('react');
var App = React.createClass({
render: function() {
return (
<div>
<h1>I am app!</h1>
</div>
);
}
});
console.log(App);
module.exports = App;
dist/index.html
<!doctype html>
<head>
<title>Redux todo</title>
</head>
<body>
<h1>Hello world</h1>
<div id='root'></div>
<script src='bundle.js'></script>
</body>
And finally here is my webpack config and package.json:
module.exports = {
// starting point
entry: [
'./src/index.js'
],
module: {
loaders: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel', // 'babel-loader' is also a legal name to reference
query: {
presets: ['es2015']
}
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
// create bundle.js file
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './dist'
}
};
package.json
{
"name": "redux-todo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/cleechtech/redux-todo.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/cleechtech/redux-todo/issues"
},
"homepage": "https://github.com/cleechtech/redux-todo#readme",
"dependencies": {
"react": "^0.14.8",
"react-dom": "^0.14.8",
"react-redux": "^4.4.1",
"redux": "^3.3.1"
},
"devDependencies": {
"babel-core": "^6.7.4",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"webpack": "^1.12.14"
}
}

You also need to add the react preset into your babel-loader config
And it must come after the es2015
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel', // 'babel-loader' is also a legal name to reference
query: {
presets: ['es2015', 'react']
}
}
The problem you're experiencing happens because for babel to know how to transpile JSX - it should know its syntax, which it does not out of the box.
As it was mentioned in the comments - you would also have to install the babel-preset-react npm package (which would obvious anyway since the babel would tell it to you on the first run anyway).
References:
https://babeljs.io/docs/plugins/preset-react/

Related

How do I fix "require is not defined" error with Webpack and Babel?

I keep getting error Uncaught ReferenceError: require is not defined in browser even with Webpack and Babel. For some reason I never had to worry about this before. I'm not sure if this error is caused by updated packages or what. I set up a very simple test application for simplicity.
package.json
{
"name": "require-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": "16.16.0"
},
"scripts": {
"build": "webpack --config webpack.config.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.18.10",
"#babel/preset-env": "^7.18.10",
"babel-loader": "^8.2.5",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0"
}
}
webpack.config.js
const path = require('path');
module.exports = {
target: "node",
mode: "production",
output: {
path: path.resolve(__dirname, 'dist'),
clean: true,
filename: (pathData) => {
return 'index.js'
},
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
}
}
src/index.js (js file before build)
const path = require('path');
console.log(path);
dist/index.js (js file after build)
(()=>{var r,e={17:r=>{"use strict";r.exports=require("path")}},t={};r=function r(o){var s=t[o];if(void 0!==s)return s.exports;var p=t[o]={exports:{}};return e[o](p,p.exports,r),p.exports}(17),console.log(r)})();
There're a few things on your code needing changed. First of all, you can't target to build for node while you run that code on browser which is wrong. Secondly, path is designed and built to run on node server specifically, however, there's a fallback for path on browser though which is called path-browserify. You can check its document to see how it works.
Anyway to sum up, you need to switch target as web in the end:
module.exports = {
target: "web",
// ...
}

webpack bundles files but index.js isn't running

I have an index.js file that imports my CSS and a few packages, but after bundling everything and starting the server I noticed that index.js wasn't running. I did a simple console.log in index.js and it isn't reached.
I copied the contents of my webpack.config file from a previous project which was working correctly, so I'm not sure if it's a file structure/path error or what not. Any thoughts?
Directory structure:
webpack.config.js:
const path = require('path')
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin')
var $ = require("jquery");
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'RecruitmentTracking.txt',
inject: 'body'
});
module.exports = {
entry: "./src/index.js", // removing the . fails the build
output: {
filename: './SiteAssets/scripts/RecruitmentTracking.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}, {
test: /\.css$/,
use: ['style-loader', 'css-loader']
}, {
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
],
},
devServer: {
disableHostCheck: true
},
devtool: 'cheap-module-eval-source-map', // this helps the browser point to the exact file in the console, helps in debug
devServer: {
contentBase: path.join(__dirname, 'src'),
historyApiFallback: true // this prevents the default browser full page refresh on form submission and link change
},
plugins: [
HtmlWebpackPluginConfig,
new webpack.ProvidePlugin({
"$": "jquery",
"jQuery": "jquery",
"window.jQuery": "jquery"
})]
}
index.js:
import "./RecruitmentTracking.css";
import 'jquery';
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
import 'jquery-ui-bundle/jquery-ui.min.js';
console.log('this is index.js');
package.json:
{
"name": "recruitmenttracking",
"version": "1.0.0",
"description": "Recruitment Initiatives Tracking",
"main": "index.js", // ----- should a more specific file path be here?
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --open --mode development",
"build": "webpack --config webpack.config.js",
"dev-server": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.2.3",
"#babel/core": "^7.4.0",
"#babel/preset-env": "^7.4.2",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.1",
"file-loader": "^3.0.1",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^0.23.1",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"webpack-dev-server": "^3.2.1"
},
"dependencies": {
"#babel/polyfill": "^7.4.0",
"axios": "^0.18.0",
"bootstrap": "^4.3.1",
"jquery": "^3.3.1",
"jquery-ui-bundle": "^1.12.1-migrate",
"pdfmake": "^0.1.54",
"popper": "^1.0.1"
}
}
What's happening here is:
1 - webpack compiles and outputs into: './SiteAssets/scripts/RecruitmentTracking.js'
2 - HtmlWebpackPlugin, will then read the template file './src/index.html', and inject RecruitmentTracking.js script inside the body.
3 - then, it outputs the result to dist/RecruitmentTracking.txt
I don't see any problem, apart from the file being a .txt and not .html. and would obviously not be interpreted by the browser.
Try outputting to an html file instead, it should work
1) For some reason you've configured the following plugin to output a .txt file. So don't expect the browser to intepret that as a html file
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'RecruitmentTracking.txt',
inject: 'body'
});
2) Also I believe that file that you're opening in the browser is /dist/index.html and that file doesn't load your js file. Try adding the following line into /dist/index.html:
<script src"./SiteAssets/scripts/RecruitmentTracking.js"></script>
3) If the above works, please still consider taking a closer look at (1)
You have named the output file in HtmlWebpackPluginConfig as RecruitmentTracking.txt. change it to index.html and it should work
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html', // webpack takes ./src/index.html as input file
filename: 'index.html', // webpack processes the above input template and should output to index.html
inject: 'body'
});

react, wepack, babel, node, npm start error

ERROR in ./main.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module '#babel/preset-es2015' from 'F:\reactapp'
at Function.module.exports [as sync] (F:\reactapp\node_modules\resolve\lib\sync.js:43:15)
at resolveStandardizedName (F:\reactapp\node_modules#babel\core\lib\config\files\plugins.js:101:31)
at resolvePreset (F:\reactapp\node_modules#babel\core\lib\config\files\plugins.js:58:10)
at loadPreset (F:\reactapp\node_modules#babel\core\lib\config\files\plugins.js:77:20)
at createDescriptor (F:\reactapp\node_modules#babel\core\lib\config\config-descriptors.js:154:9)
at items.map (F:\reactapp\node_modules#babel\core\lib\config\config-descriptors.js:109:50)
at Array.map ()
at createDescriptors (F:\reactapp\node_modules#babel\core\lib\config\config-descriptors.js:109:29)
at createPresetDescriptors (F:\reactapp\node_modules#babel\core\lib\config\config-descriptors.js:101:10)
at passPerPreset (F:\reactapp\node_modules#babel\core\lib\config\config-descriptors.js:58:96)
# multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./main.js main[2]
Child html-webpack-plugin for "index.html":
1 asset
Entrypoint undefined = index.html
[./node_modules/html-webpack-plugin/lib/loader.js!./index.html] 448 bytes {0} [built]
[./node_modules/lodash/lodash.js] 527 KiB {0} [built]
[./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 472 bytes {0} [built]
[./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 497 bytes {0} [built]
i ?wdm?: Failed to compile.
Terminate batch job (Y/N)?
package.json file:
package json file is as follows. I followed https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm
{
"name": "reactapp",
"version": "1.0.0",
"description": "demo project",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
},
"keywords": [
"[]"
],
"author": "manjunathan g",
"license": "ISC",
"dependencies": {
"#babel/cli": "^7.2.3",
"#babel/core": "^7.2.2",
"#babel/preset-react": "^7.0.0",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"webpack": "^4.28.2",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.14"
},
"devDependencies": {
"#babel/plugin-proposal-class-properties": "^7.2.3",
"#babel/preset-env": "^7.2.3",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.4",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0"
}
}
babel config:
Babel config file is as below; followed as per https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm
{
"presets":["env", "react"]
}
webpack config
webpack config is as follows:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './main.js',
output: {
path: path.join(__dirname, '/bundle'),
filename: 'index_bundle.js'
},
devServer: {
inline: true,
port: 8080
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['#babel/react', '#babel/es2015'],
plugins: ['#babel/proposal-class-properties']
}
}
]
},
plugins:[
new HtmlWebpackPlugin({
template: './index.html'
})
]
}
The #babel/preset-es2015 package has been deprecated and you can no longer install it from NPM.
The recommendation now is to use #babel/preset-env instead.
There are a lot of mistakes in your file configuration. Let me try to solve it:
.babelrc
You don't need the following devDependencies: babel-core, babel-preset-env, babel-preset-react and babel-preset-es2015. They are deprecated since Babel 7 was realeased. Substitute your code to this:
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
webpack.config.js
Since webpack 4 was released, you don't need to inform the entry and output fields (You can do it for custom configurations). By default, webpack will look for index.js file located in the src/ directory (this directory must be in the root of your project). Webpack will create the module dependency graph from this file and output the bundled file to the dist/ directory. Try to configure your webpack.config.js like this:
const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
module.exports = {
module: {
rules: [
{
test: /\.jsx$/,
exclude: /node_modules/,
use: { loader: "babel-loader" }
},
{
test: /\.html$/,
use: { loader: "html-loader" } //Install it: 'npm i -D html-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "src/index.html" // Put the index.html in the src/ directory
})
]
}
I'm not an expert in configuring webpack and I don't know if I could help you. I wrote an article on medium setting the environment to work with react, babel and webpack, but it is in portuguese. If you want to check: https://medium.com/#brunonakayabu/react-webpack-e-babel-configurando-o-ambiente-de-desenvolvimento-c7ee8a994222

Simple Webpack + React + ES6 + babel example doesn't work. Unexpected token error

am getting a parsing error while running webpack to compile the jsx syntax. Would appreciate if someone could point me to the error. I see a similar question asked Webpack, React, JSX, Babel - Unexpected token < but the solution suggested there doesn't work for me.
This is how my config files look like:
package.json
{
"name": "dropdowns",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"react": "^15.2.1",
"react-dom": "^15.2.1",
"babel-core": "^6.11.4",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.11.1"
},
"devDependencies": {
"webpack": "^1.13.1",
"webpack-dev-server": "^1.14.1"
},
"author": "",
"license": "ISC"
}
my webpack.config.js file is
module.exports = {
context: __dirname + "/app",
entry: "./main.js",
output: {
filename: "bundle.js",
path: __dirname + "/dist"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
};
In a local app folder I have main.js and IdMappingOptions.js as follows:
// in IdMappingOptions.js
import React from 'react';
class IdMappingOptions extends React.Component {
render () {
return <span>Hello!</span>
}
}
export default IdMappingOptions;
// in main.js
import React from 'react';
import { render } from 'react-dom';
import IdMappingOptions from './IdMappingOptions';
render(
<IdMappingOptions/>, document.body
);
when running node_modules/.bin/webpack I get the following error trace:
Hash: 396f0bfb9d565b6f60f0
Version: webpack 1.13.1
Time: 37ms
[0] ./main.js 0 bytes [built] [failed]
ERROR in ./main.js
Module parse failed: /scratch/parallel/repository/dropdowns/app/main.js Unexpected token (6:4)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (6:4)
at Parser.pp.raise (/scratch/parallel/repository/dropdowns/node_module/acorn/dist/acorn.js:923:13)
Edit:
as per the comments below fixed the test pattern and added babel-core in the webpack.config.js. Here is my
Your test seems faulty:
test: "/.js$"
Try this:
test: /\.js$/
You need babel-core to use babel in your project. (https://github.com/babel/babel-loader#installation).
npm install --save-dev babel-core

Syntax error in ReactJS

I'm starting to learn ReactJS and I'm following instructions in a book on getting started. My directory structure looks like this:
app/App.js
node_modules
index.html
package.json
webpack.config.js
I think that the culprit of the problem is this error message from CLI:
ERROR in ./app/App.js
Module build failed: SyntaxError: c:/code/pro-react/my-app/app/App.js: Unexpected token (6:6)
4 | render() {
5 | return (
> 6 | <h1>Hello World</h1>
| ^
7 | );
8 | }
9 | }
The contents of App.js are:
import React from 'react';
class Hello extends React.Component {
render() {
return (
<h1>Hello World</h1>
);
}
}
React.render(<Hello />, document.getElementById('root'));
Here is the contents of package.json:
{
"name": "my-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node_modules/.bin/webpack-dev-server --progress",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.4.5",
"babel-loader": "^6.2.1",
"webpack": "^1.12.11",
"webpack-dev-server": "^1.14.1"
},
"dependencies": {
"react": "^0.14.6"
}
}
And the contents of webpack.config.js are:
module.exports = {
entry: __dirname + "/app/App.js",
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel'
}]
}
};
I launch the application from CLI with the command:
npm start
And when I go to http://localhost:8080 in Dev Tools there is an error message:
GET http://localhost:8080/bundle.js 404 (Not Found)
But as I said, I think that the culprit is that it doesn't like the syntax so it doesn't make the bundle.js file. Please let me know what I'm doing wrong.
I think it happens because you are using babel-6 without babel presets, in this case you need babel-preset-es2015 and babel-preset-react.,
# For ES6/ES2015 support
npm install babel-preset-es2015 --save-dev
# Fot JSX support
npm install babel-preset-react --save-dev
then change webpack config
{
test: /\.jsx?$/,
loader: 'babel',
query: {
presets: ['es2015', 'react'],
}
}
or instead of using query you can create .babelrc file with content
{
"presets": ["es2015", "react"]
}
also you need install react-dom and use ReactDOM.render instaed or React.render

Categories

Resources