Webpack Module build failed when importing React components - javascript

I'm working on a project to integrate React and ASP.Net together. I've made the initial Hello World and every works as expected (not hard :p). I'm using webpack with babel-loader to generate my `bundle.js.
import React from 'react'
import ReactDOM from 'react-dom'
ReactDOM.render(<h1>LPMU</h1>, document.getElementById('root'))
This is my webpack.config.js file:
module.exports = {
context: __dirname,
entry: "./App.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
watch: true,
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['babel-preset-env', 'babel-preset-react']
}
}
}
]
}
}
After this worked out, I tried to add my App.js component and all other components into my react folder, inside Scripts on my ASP.NET project. I'm not doing the export default App since I'm using the ReactDOM.render(). I import my components into my App.js as usual:
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import './App.css';
import Header from './Header';
import Footer from './Footer';
import Landing from './Landing';
import * as lpmuGlobal from './lpmu-global';
And then I just render the App component:
ReactDOM.render(<App />, document.getElementById('root'))
Now when I run npm run webpack again, I get 2 problems, which are the following:
size name module status
704 B 0 ./App.js built failed ✖
Δt 596ms (1 asset hidden)
./App.js
0:0 error Module build failed (from ./node_modules/babel-loader/lib/index.js):
configuration
0:0 warning The 'mode' option has not been set, webpack will fallback to
'production' for this value. Set 'mode' option to 'development' or
'production' to enable defaults for each environment.
✖ 2 problems (1 error, 1 warning)
I've been searching for a solution, but since I'm really new to webpack, I don't know what happens, if I need anything else on my webpack.config.js, if I have to import my components in any other way or whatever.
ALso this is my json.package:
{
"name": "lpmu-react-app",
"version": "1.0.0",
"description": "Integración de ReactJS con ASP.NET",
"main": "App.js",
"scripts": {
"start": "react-scripts start",
"webpack": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "DPS",
"license": "ISC",
"dependencies": {
"react": "^16.4.0",
"react-dom": "^16.4.0",
"webpack-command": "^0.2.1"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"webpack": "^4.12.0",
"webpack-cli": "^3.0.4"
}
}
Thanks

The error is because you have not added a .babelrc file or babel options to your package.json file to provide babel options.
In order to enable the preset you have to define it in your .babelrc
file
Add babel option to your package.json as such :
package.json:
{
"name": "lpmu-react-app",
"version": "1.0.0",
"description": "Integración de ReactJS con ASP.NET",
"main": "App.js",
"scripts": {
"start": "react-scripts start",
"webpack": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"babel":{
"presets": ["env","react"]
}
"author": "DPS",
"license": "ISC",
"dependencies": {
"react": "^16.4.0",
"react-dom": "^16.4.0",
"webpack-command": "^0.2.1"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"webpack": "^4.12.0",
"webpack-cli": "^3.0.4"
}
}
Go through the below links for further clarification:
https://babeljs.io/docs/en/babelrc.html
https://babeljs.io/en/setup/#installation
About the warning :
Webpack 4 needs you to include the mode option to your configuration, as you would usually want to have development and production configurations separate.
Go through the link below which explains in detail how to set configurations.
https://www.valentinog.com/blog/webpack-4-tutorial/
module.exports = {
context: __dirname,
entry: "./App.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
watch: true,
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['babel-preset-env', 'babel-preset-react']
}
}
}
]
}
}
Hope that helps :)

Related

Event handling is not working in a fresh react project

I've been trying my first steps with react.js and after playing around a bit (installing Bootstrap, adding some loaders for LESS & Co.) at some point the event handlers (onSubmit, onChange) stopped working. At first, I thought I just messed up my code.
However, when I copy the example for a controlled components form into a freshly initialized npm project with React 17.0.2, these handlers are still not working as expected. E.g. the onSubmit handler:
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
Neither does the alert show, nor is the default event handling prevented. The page simply reloads when I hit the submit button.
For example, if I put an alert into the constructor it is being shown.
Here is the full package.json
{
"name": "app-retry",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"start": "webpack-dev-server --open",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"#babel/core": "^7.16.12",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.16.7",
"babel-loader": "^8.2.3",
"html-webpack-plugin": "^5.5.0",
"webpack": "^5.67.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.3"
}
}
and here is the full webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: path.resolve(__dirname, 'src', 'index.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
dev: {
hot: true,
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
// attach the presets to the loader (most projects use .babelrc file instead)
presets: ["#babel/preset-env", "#babel/preset-react"]
}
}
]
},
plugins: [new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'src', 'index.html') })]
};
The index.js is
import React from "react";
import ReactDOM from "react-dom";
// lines as copied from the react example
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
and finally the index.html template
<html>
<head>
<title>Hello world App</title>
</head>
<body>
<div id="root"></div>
<script src="./bundle.js"></script>
</body>
</html>
What am I doing wrong? Is the example code wrong or is there a flaw in my setup?

ERROR in ./src/index.js Module build failed (from ./node_modules/babel-loader/lib/index.js):

I'm trying to set up ReactJs from scratch but npm start, dev, build, and watch are throwing the error below:
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:\da4na4\web\stocker\src\index.js: Unexpected character '�' (1:0)
I have setup package.json, webpack.config.js, and .babelrc configurations. I have equally tried out previous answers on Stack Overflow, yet the issue persist. Below are the configurations of the respective files:
package.json
{
"name": "stocker",
"version": "1.0.0",
"description": "A product inventory web app to help you keep track of your stocks and meet demands",
"main": "webpack.config.js",
"scripts": {
"test": "jest ./src/tests",
"dev": "webpack --mode development",
"build": "webpack --mode production",
"watch": "webpack --watch",
"start": "webpack serve --mode development --open --hot"
},
"keywords": [
"products",
"Inventory"
],
"author": "Emmanuel Joshua",
"license": "MIT",
"devDependencies": {
"#babel/core": "^7.12.16",
"#babel/preset-env": "^7.12.16",
"#babel/preset-react": "^7.12.13",
"#webpack-cli/serve": "^1.3.0",
"babel-loader": "^8.2.2",
"css-loader": "^5.0.2",
"html-loader": "^1.3.2",
"html-webpack-plugin": "^5.0.0",
"jest": "^26.6.3",
"jsdom": "^16.4.0",
"sass-loader": "^11.0.1",
"style-loader": "^2.0.0",
"webpack": "^5.21.2",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"react": "^17.0.1",
"react-dom": "^17.0.1"
}
}
webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const htmlPlugin = new HtmlWebpackPlugin({
template: "./src/index.html",
filename: "index.html"
});
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "public"),
filename: "js/app.min.bundle.js",
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.(scss|css)$/, use: ["sass-loader", "css-loader", "style-loader"]
},
{
test: /\.(html)$/, use: ["html-loader"]
}
],
},
plugins: [htmlPlugin],
target:"node",
devServer:{
port: 3000,
contentBase: path.resolve(__dirname, "public")
},
resolve: {
extensions: ["*", ".js", ".jsx"],
},
};
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
These are the index.js and the App.js files
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './js/App';
ReactDOM.render(
<App firstname={"Joshua"} />,
document.getElementById("root")
)
js/App.js
import React, {Component} from 'react';
class App extends Component{
constructor(props){
super(props);
}
render(){
return(
<h1>Hello {this.props.firstname}, Welcome to our Website!</h1>
)
}
}
export default App;
This tripped me a while. I found out one of the reasons is because of the directory naming path.
I used # for a folder name and it gave me the same error you're reading into.
e.g. my path
C:/Users/johndoes/codes/# wip/project1/sub/
My suggestion is looking at the pathing and seeing if everything is on the right place and referred to correctly.

Plugin/Preset files are not allowed to export objects, only functions. Removing and keeping babel installs? Selection with webpack?

I'm trying to learn how to write a React App and set up from practically scratch.
I keep trying to run webpack --config webpack.dev.config.js.
I keep getting this error. And I've tried using different loaders and presets.
What is wrong with my setup? Is it my npm node modules are outdated?
I've tried updating all my presets, loaders and even babel itself.
Error:
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Plugin/Preset files are not allowed to export objects, only functions. In /Users/kyle.calica-steinhil/Code/react-components/react-imgur-album/node_modules/babel-preset-es2015/lib/index.js
at createDescriptor (/Users/kyle.calica-steinhil/Code/react-components/react-imgur-album/node_modules/#babel/core/lib/config/config-descriptors.js:178:11)
at items.map (/Users/kyle.calica-steinhil/Code/react-components/react-imgur-album/node_modules/#babel/core/lib/config/config-descriptors.js:109:50)
at Array.map (<anonymous>)
webpack.dev.config.js:
var path = require('path');
module.exports = {
mode: 'development',
// context: path.resolve(__dirname, 'src'),
entry: path.resolve(__dirname,'src/index.js'),
output: {
filename: 'main.js',
libraryTarget: "commonjs2"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['es2015','react'],
plugins: ['transform-class-properties']
}
}
]
}
]
},
resolve: {
extensions: ['.js']
}
};
package.json :
{
"name": "react-imgur-album",
"version": "0.0.1",
"description": "React Component for displaying images in an Imgur Album",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.dev.config.js --progress --display-error-details"
},
"keywords": [
"imgur",
"react",
"react-components",
"component",
"images",
"photos",
"pics"
],
"author": "Kyle Calica",
"license": "ISC",
"dependencies": {
"#babel/preset-react": "^7.0.0",
"react-dom": "^16.5.2"
},
"devDependencies": {
"#babel/cli": "^7.1.2",
"#babel/core": "^7.1.2",
"#babel/plugin-proposal-class-properties": "^7.1.0",
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.4",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"eslint": "^5.7.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-jsx-a11y": "^6.1.2",
"eslint-plugin-react": "^7.11.1",
"fixed": "^0.3.0",
"it": "^1.1.1",
"path": "^0.12.7",
"react": "^16.5.2",
"webpack": "^4.22.0",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.9"
}
}
index.js:
import React, { Component } from 'react';
var imgurAPI = 'https://api.imgur.com/3/album/';
export default class ImgurAlbum extends Component {
constructor(props){
super(props);
this.state = {
imgurPosts: [],
isLoading: true
};
}
componentDidMount(){
fetch(imgurAPI + this.props.album + '/images',{
'headers':{
'Authorizathion': 'client-id'
}
}).then(res => res.json())
.then(data => console.log(data));
}
render(){
return(
<div>
<h1>hi!</h1>
</div>
);
}
}
I notice I have two babel cores installed, I don't know how to remove one, or which one to keep. Or even how to select which one with webpack?
I found my solution!
It's a babel mismatch.
I had an old babel-core and babel-presets installed.
In Babel 7, it is best to install using:
npm i #babel/preset-react #babel/preset-env
then in your .babelrc:
{
"presets" : ["#babel/preset-env","#babel/preset-react"]
}
I also uninstalled the old babel-preset-react and babel-preset-es2015 for safe measure.
Still learning so I might be missing steps or understanding here. Please add if you believe you need more information or if I am wrong about anything, but I was able to get mine to build

Webpack/React: Following egghead.io tutorial but getting an error: You may need an appropriate loader to handle this file type

I've just started following this tutorial.
I've gone through the first video three or four times now. When I try to run the application, I get the following error in the console:
ERROR in ./main.js
Module parse failed: /Users/newuser/projects/js101/react-egghead/main.js Unexpected token (5:16)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (5:16)
at Parser.pp.raise (/Users/newuser/projects/js101/react-egghead/node_modules/acorn/dist/acorn.js:920:13)
...
I've looked at similar questions on SO but none seem to have an answer for me.
Here's my webpack.config.js file:
module.exports = {
entry: './main.js',
output: {
path: './',
filename: 'index.js'
},
devServer: {
inline: true,
port: 3333
},
moudle: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
This is what package.json looks like:
{
"name": "react-egghead",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^15.0.2",
"react-dom": "^15.0.2"
},
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.9.0",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.5.0",
"webpack": "^1.13.0",
"webpack-dev-server": "^1.14.1"
}
}
And, although it's not mentioned in the video, I've added a .babelrc file: (which I have now removed)
{
"presets": ["es2015", "stage-0", "react"]
}
This is where the parse fails (line 5):
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App.js'
ReactDOM.render(<App />, document.getElementById('app'))
I really don't know what to try next. Is it a problem with my environment set up or is it a problem with the code in main.js?
Any help would be appreciated.
You have a typo in your webpack config. Instead of module you typed moudle, so your loader configs are actually ignored by webpack :)

babel-loader 6.0.0 doesn't work correct

I am using webpack this is my
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/app',
output: {
path: path.join(__dirname, '/public'),
filename: 'bundle.js'
},
watch: true,
watchOptions: {
aggregateTimeout: 100
},
devtool: 'source-map',
module: {
loaders: [{
test: /\.js$/,
loader: "babel-loader"
}]
}
}
and this my file from entry point
app.js
import React from 'react'
without anything, just simple line of code.
When i am trying to run webpack from command line and i got the next error
app.js Line 1: Unexpected token You may need an appropriate loader to
handle this file type. | import React from 'react';
package.json
{
"name": "a-b-c",
"version": "1.0.0",
"main": "server.js",
"dependencies": {
"babel-loader": "^6.0.0",
"react": "^0.14.1",
"webpack": "^1.12.2"
},
"devDependencies": {
"babel-core": "^6.0.14"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": ""
}
Also, when i changed ES6 syntax in my app.js file to ES5 then it works well.
Any suggestions?
Thanks in advance.
I've found out. The problem was with babel-loader and to fix this issue you need to install
npm install babel-loader babel-core babel-preset-es2015
and add to your webpack.config.js file next lines
loader: 'babel?presets[]=es2015'
Source of information
Thanks

Categories