How do you use webpack-merge and react? - javascript

I have been trying to make a webpack config for a react based app, it was working before I started using webpack-merge and had the single webpack.config.js file. I have done a lot of reading and I have not been able to find a solution and was wondering if there is a way for me to have a split webpack config.
Any help would be much appreciated!
The error I am getting is:
ERROR in ./src/index.js 8:4
Module parse failed: Unexpected token (8:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| ReactDOM.render(
> <App title={title} />,
| document.getElementById('app')
| );
webpack 5.19.0 compiled with 1 error in 17 ms
i 「wdm」: Failed to compile.
My webpack config files:
webpack.common.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('html-webpack-plugin');
module.exports = {
entry: path.resolve(__dirname, '..', './src/index.js'),
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['#babel-loader'],
},
],
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
output: {
path: path.resolve(__dirname, '..', './dist'),
filename: 'bundle.js',
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, '..', './src/index.html')
}),
],
devServer: {
contentBase: path.resolve(__dirname, '..', './dist'),
hot: true,
},
};
webpack.config.js
const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.common.js');
module.exports = ({ env }) => {
const envConfig = require(`./webpack.${env}.js`);
return merge(commonConfig, envConfig);
};
webpack.dev.js
module.exports = {
mode: 'development',
devtool: 'eval-source-map',
};
webpack.prod.js
module.exports = {
mode: 'production',
devtool: 'source-map',
};
My other files:
App.js
import React from "react";
const App = ({ title }) =>
<div>{title}</div>;
export default App;
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Hello World!</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<div id='app'></div>
</body>
</html>
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "../App";
ReactDOM.render(
<App title={title} />,
document.getElementById('app')
);
module.hot.accept();
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
package.json
...
"scripts": {
"start": "webpack serve --config build-utils/webpack.dev.js --env env=dev",
"build": "webpack --config build-utils/webpack.prod.js --env env=prod",
"test": "echo \"Error: no test specified\" && exit 1"
},
...
"devDependencies": {
"#babel/core": "^7.12.10",
"#babel/preset-env": "^7.12.11",
"#babel/preset-react": "^7.12.10",
"babel-cli": "^6.26.0",
"babel-loader": "^8.2.2",
"clean-webpack-plugin": "^3.0.0",
"html-webpack-plugin": "^4.5.1",
"react-hot-loader": "^4.13.0",
"webpack": "^5.19.0",
"webpack-cli": "^4.4.0",
"webpack-dev-server": "^3.11.2",
"webpack-merge": "^5.7.3"
},
"dependencies": {
"react": "^17.0.1",
"react-dom": "^17.0.1"
}

Related

SyntaxError in ./index.html

I'm trying to convert my create-react-app to a Webpack compatible app.
I can't understand clearly what I'm done and I often get into an error:
ERROR in ./index.html
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /mnt/c/Users/.../index.html: Unexpected token (1:0)
> 1 | <!doctype html>
| ^
2 | <html>
3 | <head>
4 | <title>Getting Started</title>
at Object._raise [...]
This happens after launching npm start
This is my configuration:
Structure
index.html
webpack.config.js
babelrc
src/index.js
package.json
./index.html
<!doctype html>
<html>
<head>
<title>Getting Started</title>
<script src="https://unpkg.com/lodash#4.16.6"></script>
</head>
<body>
<script src="./src/index.js"></script>
</body>
</html>
./src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
./webpack.config.js
const webpack = require('webpack');
const path = require('path');
const config = {
entry: [
'react-hot-loader/patch',
'./index.html'
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$|jsx$|html/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['#babel/preset-env', '#babel/react']
}
}
]
},
resolve: {
extensions: [
'.js',
'.jsx',
'.html'
],
alias: {
'react-dom': '#hot-loader/react-dom'
}
},
devServer: {
contentBase: './dist'
}
};
module.exports = config;
Finally, my ./.babelrc
{
"plugins": ["#babel/transform-react-jsx"],
"ignore": [
"foo.js",
"bar/**/*.js"
]
}
I've this dependencies in my package.json:
"devDependencies": {
"#babel/core": "^7.11.6",
"#babel/preset-env": "^7.11.5",
"#babel/preset-es2015": "^7.0.0-beta.53",
"#babel/preset-react": "^7.10.4",
"#babel/preset-typescript": "^7.10.4",
"#hot-loader/react-dom": "^17.0.0-rc.2",
"babel-loader": "^8.1.0",
"babel-plugin-import": "^1.13.0",
"css-loader": "^4.3.0",
"react-hot-loader": "^4.5.3",
"style-loader": "^1.2.1",
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
}
You're using a javascript loader for your html, this is not going to work.
You should use the html-loader instead

How to resolve " Error "Cannot find module 'babel-preset-react' ", when working with babel in react

I am learning React and flask and have been trying to set it up primarly using this video and the steps there.
https://www.youtube.com/watch?v=TKIHpoF8ZIk
Though when trying to get babel to work and running "npm run build" I get the response "Error Cannot find module 'babel-preset-react'". I tried this solution Cannot find module 'babel-preset-react' but could still not get it to work.
Does anyone know how to solve this issue? Thanks
My code:
package.json file
{
"name": "react_test",
"version": "1.0.0",
"description": "react test",
"main": "index.jsx",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --progress -d --config webpack.config.js -watch",
"build": "webpack"
},
"keywords": [
"python",
"react"
],
"babel": {
"presets": [
"react",
"es2015"
]
},
"author": "J",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.8.3",
"#babel/preset-env": "^7.8.3",
"#babel/preset-react": "^7.8.3",
"babel-loader": "^8.0.6",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10"
},
"dependencies": {}
}
My webpack.config.js file
const webpack = require('webpack');
const path = require('path')
const config = {
entry: __dirname + '/js/index.jsx',
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist/',
// path: __dirname + '/dist',
filename: 'bundle.js'
},
resolve:{
extensions: ['.js', '.jsx','.css']
},
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
use:'babel-loader'
}
]
}
};
module.exports = config;
index.html file
<!doctype html>
<html>
<body>
<div id = "content" />
<script src="dist/bundle.js" type = "text/javascript">
</script>
</body>
</html>
index.jsx file
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("content"));
app.jsx file
import React from "react";
export default class App extends React.Component{
render(){
return <p> Hello React </p>;
}
}

React index.html rendered but react component does not

i couldn't figure out why ReactDOM does't render my simple component but seems to keep and render just the plain index.html
package.json
{
"name": "client2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "babel-node buildScripts/server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.3",
"path": "^0.12.7"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.8.3",
"webpack-dev-middleware": "^3.1.3"
},
"babel": {
"presets": [
"es2015",
"react"
],
"env": {
"presets": [
"react-hmre"
]
}
}
}
webpack.config.dev.js
import webpack from 'webpack'
import path from 'path'
const HtmlWebpackPlugin = require('html-webpack-plugin');
export default {
devtool: 'inline-source-map',
entry: [
path.resolve(__dirname, 'src/index.js')
],
output: {
path: path.resolve(__dirname, 'src'),
publicPath: '/',
filename: 'bundle.js'
},
module:{
rules:[
{test: /\.js$/ , loader:'babel-loader', exclude: '/node_modules/'},
{test: /\.jsx$/ , loader:'babel-loader', exclude: '/node_modules/'}
]
},
plugins:[
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
inject: 'body'
})
]
}
buildScript/server.js
import express from 'express';
import path from 'path';
import webpack from 'webpack';
import config from '../webpack.config.dev';
const compiler = webpack(config);
/* var express = require('express')
var path = require('path') */
const port = 8081;
const app = express();
app.listen(port, function (error) {
if(error) {
console.log(error);
}
});
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, '../src/index.html'));
});
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(){
super();
console.log("App Hello")
}
render(){
return(
<div>
<h1>Howdy from React!</h1>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hey!</title>
</head>
<body>
<div id="root"></div>
<h1>Hello World!</h1>
</body>
</html>
The only response i get is
With no logs from my index.js react "App".
I've been trying several solutions, none happened aside from my express server not working. What might be the problem here ? Thank you very much !
As I wrote in comment, you should include your js
<html lang="en">
<head>
<title>Hey!</title>
</head>
<body>
<div id="root"></div>
<h1>Hello World!</h1>
<script src="/bundle.js"></script>
</body>
</html>
Your html file needs to link to bundle.js
<script src="/bundle.js"></script>
Thanks for Leo Odishvili and Ben West for helping above - the answer is really adding <script src="/bundle.js"></script> to the index.html
The only change was to
change /bundles.js to "./webservice_entrypoint/bundle.js"as webservice_entrypoint would be the url path to my react app.
Thanks everyone !
Also you can check the "html-webpack-plugin" and add the plugin to the "plugins" configuration of the webpack.config.js, this will allow you to use any template html file from inside your src directly and bundle it in the dist/ folder with the included script tag already compiled and added. It is really an useful plugin.

Hot Module Replacement with Webpack, Express & Babel (babel-loader) not working with React Components (Error: Ignored an update to unaccepted module)

I am new to React webpack and such and I am trying to implement Hot Module replacement into my workflow. I am using webpack, express, Babel ES6 with React and I believe I have all the loaders that i need.
I have got HMR working for my CSS files and it updates CSS perfectly but for some reason, when I try and update a React component, I get the following error and have to refresh the page in order to see my changes. I've been struggling the whole day so any assistance would be greatly received! The error I get is the following (my code follows afterward):
>Ignored an update to unaccepted module 28 -> 17
>
[HMR] The following modules couldn't be hot updated: (Full reload needed)
This is usually because the modules which have changed (and their parents) do not know how to hot reload themselves. See https://webpack.js.org/concepts/hot-module-replacement/ for more details.
>
[HMR] - ./app/scripts/libs/index.js
index.js (Entry)
import React from 'react';
import ReactDOM from 'react-dom';
import style from 'css/main.css';
import Sections from 'components/Sections/index.js';
ReactDOM.render(
<div>
<h2>Hek</h2>
<Sections></Sections>
</div>,
document.getElementById('app')
)
console.log('check for me');
index.js (Sections Component)
import React from 'react';
import ReactDOM from 'react-dom';
export class Sections extends React.Component{
render(){
return(
<div>
<h1>Yo yo yo wahts</h1>
<p>hlfgdfd</p>
</div>
)
}
}
module.exports = Sections;
BuildScript.js
'use strict';
var express = require('express'); //get the express module
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var app = express(); //create a new instance of that class
var config = require('../../../webpack.config.js');
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}));
app.use(webpackHotMiddleware(compiler));
app.listen(3000, function () {
// return console.log('Example app listening on port 3000!');
});
Webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: [ 'webpack-hot-middleware/client' , './app/scripts/libs/index.js'], //Can also use "main" property
output: {
path: path.resolve(__dirname, 'tmp'), //resolves the absolute path
filename: '[name].bundle.js', //
publicPath: '/'
},
devtool: 'inline-source-map',
resolve:{
alias: {
components: path.resolve(__dirname, 'app/scripts/components'),
fonts: path.resolve(__dirname, 'app/scripts/fonts'),
images: path.resolve(__dirname, 'app/images'),
sass: path.resolve(__dirname, 'app/styles/sass'),
css: path.resolve(__dirname, 'app/styles/css')
}
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'] //to use the CSS imported - in your index.js file you
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(jpg|png|svg|gif)$/,
use:['file-loader']
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader']
},
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['env', 'react']
}
}
]
},
plugins:[
new HtmlWebpackPlugin({
title: 'African Banker Awards 2018',
template: './app/scripts/libs/template.ejs',
inject: 'body'
}),
new CleanWebpackPlugin(['tmp']),
new webpack.HotModuleReplacementPlugin()
//new UglifyJsPlugin()
]
};
NPM Packages Installed
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^0.1.17",
"css-loader": "^0.28.7",
"eslint": "^4.10.0",
"file-loader": "^1.1.5",
"html-webpack-plugin": "^2.30.1",
"install": "^0.10.1",
"npm": "^5.5.1",
"sass-loader": "^6.0.6",
"style-loader": "^0.19.0",
"uglifyjs-webpack-plugin": "^1.1.4",
"webpack": "^3.10.0",
"webpack-dev-middleware": "^2.0.1",
"webpack-hot-middleware": "^2.21.0"
}
}

Unable to load ReactJS resource in the browser using Babel and Webpack

I'm trying to learn ReactJS by running a basic program.
webpack.config.js
var config = {
entry: './main.js',
output: {
path: './',
filename: 'index.js'
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.experts = config;
package.json
{
"name": "reactapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --hot"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.11.4",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.11.1",
"react": "^15.2.1",
"react-dom": "^15.2.1",
"webpack": "^1.13.1",
"webpack-dev-server": "^1.14.1"
}
}
App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
"Hello, world."
</div>
);
}
}
export default App;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="utf-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script type="text/javascript" src = "index.js"></script>
</body>
</html>
On starting the server, I see an empty page with no contents. The HTML page is there but the part which is to be added to the DOM by React can't be seen.
index.js is set as the file which will contain our bundled app but the browser's console shows 'Faile to load resource index.js(404)' error. If I change the src attribute of script tag in HTML to main.js, I get a SyntaxError with the import statement.
I suspect the problem is with not correctly linking Babel or some other dependency with my package.
Inside webpack.config.js there is typo, must be exports instead of experts
module.exports = config;
^
in this case you don't export config from webpack.config.js, and webpack doesn't know about your custom configuration and uses default config.
I think the webpack.config.jswill be like
devtool: 'eval',
entry: './src/index',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/',
},
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/,
include: __dirname,
}],
}
and the <script>
<script type="text/javascript" src = "/static/bundle.js"></script>

Categories

Resources