Webpack/Babel installation for ReactJS - javascript

I just started learning ReactJS and came across something called as webpack which is basically a module bundler.
Somehow,I'm stuck with the configuration of the same and the following error keeps coming.
ERROR in ./src/index.js 7:16
Module parse failed: Unexpected token (7:16)
You may need an appropriate loader to handle this file type.
render()
{
return (<div> <h1> Hi </h1> </div>);
}
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! reactsetup#1.0.0 start: webpack --mode=development ./src/index.js -o bundle.js
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the reactsetup#1.0.0 start script.
Here is my Package.json
{
"name": "reactsetup",
"version": "1.0.0",
"main": "./src/index.js",
"dependencies": {
"babel-preset-es2015": "^6.24.1",
"bundle-loader": "^0.5.6",
"react": "^16.4.1",
"react-dom": "^16.4.1"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"webpack": "^4.12.0",
"webpack-dev-server": "^3.1.4"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack --mode=development ./src/index.js -o bundle.js",
"build": "webpack -d && cp index.html dist/index.html && webpack-dev-server --content-base src/ --inline --hot",
"dev-start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"description": ""
}
index.js
import React from "react"
import {render} from "react-dom"
class App extends React.Component {
render()
{
return (<div> <h1> Hi </h1> </div>);
}
}
render(<App/>, window.document.getElementById("app"));
web.config.js
var path = require("path");
var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");
var config = {
entry: SRC_DIR + "index.js",
output: {
path: DIST_DIR,
filename: "bundle.js"
},
module: {
rules: [ {
test: /\.js?/,
use: {
loader: "babel-loader",
exclude: /node_modules/,
query: {
presets: ["react", "es2015"]
}
}
}
]
}
};
module.exports = config
And lastly, index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
PS: This is my first question ever on stackoverflow. Apologies for the flaws,if any.

It seems there are a couple of things
rename web.config.js to webpack.config.js
install babel-preset-react
change your HTML to the following
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="app"></div>
<script src="./dist/bundle.js"></script>
</body>
</html>
webpack.config.js
var path = require('path');
var DIST_DIR = path.resolve(__dirname, 'dist');
var SRC_DIR = path.resolve(__dirname, 'src');
var config = {
entry: SRC_DIR + '/index.js',
output: {
path: DIST_DIR,
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js?/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['react', 'es2015'],
},
},
},
],
},
};
module.exports = config;
One tip, use create react app to start fast with react :)

the default name for config is "webpack.config.js", not the "web.config.js". And you don't pass the "--config" property either. So it looks like your webpack config is not used at all.
I believe, renaming config to the "webpack.config.js" could help you

The easiest way for a beginner to set-up the React environment is to use create-react-app.
I'm assuming that you already have node installed. If not a quick Google search will instruct you how to install nodejs.
After that run the following command in the directory where you want to create the project
npm install -g create-react-app
create-react-app my-app
cd my-app
npm start
Then open your browser and go to localhost:3000 and you should see your react template.
More information on create-react-app can be found via the following links
github page
react official documentation

Related

Exposing variables from a library with webpack

I don't seem to understand how webpack works. I would like to create a plain javascript library with some reusable components that I can use in other applications and in script tags in the html. So I tried to make a very simple library that exposes one variable containing a string. Should be simple I thought, but can't seem to get it to work.
My webpack.config.js:
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
library: {
name: 'mypack',
type: 'umd',
},
},
devtool: 'source-map',
devServer: {
watchContentBase: true,
contentBase: path.resolve(__dirname, 'dist'),
port: 9000
},
module: {
rules: [
{
test:/\.css$/,
use:['style-loader', 'css-loader']
}
]
},
}
My package.json:
{
"name": "mypack",
"version": "0.0.1",
"main": "./src/app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --mode production",
"start": "webpack ./src/app.js -d eval --watch --mode development",
"dev": "npx webpack serve"
},
"author": "me",
"license": "ISC",
"devDependencies": {
"css-loader": "^6.0.0",
"webpack": "^5.44.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"style-loader": "^3.2.1"
}
}
My src/app.js
let myvar = "test";
export {myvar};
My dist/index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8"><title>test</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<script src="main.js"></script>
</head>
<body>
Test
<script>
console.log(mypack.myvar);
</script>
</body>
</html>
mypack.myvar gives an 'undefined' in the console. mypack seem to be an empty object {}.
How can I access myvar in my package? What am I doing wrong?
Of course, this is only a dummy, in reality I would like to expose objects from the package.
In the end it seems to be a problem with the webppack-dev-server.
If I comment out the line 'contentBase: path.resolve(_dirname, 'dist'),' from the webpack.config.js, copy the index.html to the root of my package and change the script tag source to "dist/index_bundle.js" then it works.
Not sure what is going on there, the script seems to load just fine in the situation above (in the sourceview in the browser, I can click the link and I see the generated javascript) but doesn't seem to be working at all. But that's another question.

"Failed to resolve module specifier" or "window is not defined" when I import WASM in JS worker

I am trying to import my WASM library (written in Rust) inside a JS worker. And I get the error:
Uncaught (in promise) TypeError: Failed to resolve module specifier 'mylib'
Or if I try to use worker-loader the error is different, but in the same line:
window is not defined
What is the nature of the errors and how am I supposed to fix it?
The details are represented below. I tried to make the example as minimal as possible (without worker-loader).
The structure of my project is:
wasm-worker-example/
mylib/
pkg/*
src/
lib.rs
Cargo.toml
www/
bundles/*
node_modules/*
index.html
index.js
my.worker.js
package.js
webpack.config.js
lib.rs
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn concat(a: &str, b: &str) -> String {
a.to_string() + b
}
Cargo.toml
[package]
name = "mylib"
version = "0.1.0"
authors = ["Alexander <mail#fomalhaut.su>"]
edition = "2018"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
package.json
{
"name": "www",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"mylib": "file:../mylib/pkg",
"#babel/core": "^7.9.6",
"babel-loader": "^8.1.0",
"webpack": "^4.43.0",
"webpack-bundle-tracker": "^1.0.0-alpha.1",
"webpack-cli": "^3.3.11"
}
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const BundleTracker = require('webpack-bundle-tracker');
module.exports = {
mode: 'development',
context: __dirname,
entry: './index',
output: {
path: path.resolve('./bundles/'),
filename: 'app.js',
publicPath: "/bundles/"
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
],
},
};
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="bundles/app.js"></script>
</head>
<body>
</body>
</html>
index.js
import("mylib").then(wasm => {
// It works fine
console.log(wasm.concat("qwe", "rty"));
var worker = new Worker("my.worker.js");
worker.postMessage('Message to worker');
});
my.worker.js
// Error: Uncaught (in promise) TypeError: Failed to resolve module specifier 'mylib'
import("mylib").then(wasm => {
// Not reached
console.log(wasm.concat("qwe", "rty"));
self.addEventListener('message', e => {
console.log(e.data);
});
});
I prepare mylib with (in mylib):
wasm-pack build
For frontend (in www):
npm install
./node_modules/.bin/webpack
To run (in www):
http-server

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

Webpack and React -- Unexpected token

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/

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