Missing Loader, Webpack and React - reactjs

I am building an application using Reactstrap and Webpack. I am struggling with Webpack and React. I am tring to run my react-dev server but I am running into this error in my terminal:
ericpark-macbookpro3:mvp ericpark$ npm run react-dev
> github-fetcher-fullstack-v2#1.0.0 react-dev /Users/ericpark/Desktop/mvp
> webpack -d --watch
Webpack is watching the files…
Hash: d1e3cad44a718dd4af71
Version: webpack 2.7.0
Time: 64ms
Asset Size Chunks Chunk Names
bundle.js 3.35 kB 0 [emitted] main
[0] ./react-client/src/index.jsx 298 bytes {0} [built] [failed] [1 error]
ERROR in ./react-client/src/index.jsx
Module parse failed: /Users/ericpark/Desktop/mvp/react-client/src/index.jsx Unexpected token (61:6)
You may need an appropriate loader to handle this file type.
| render() {
| return (
| <div className="App">
| <Navbar></Navbar>
| <Container>
It looks like I am missing a loader. Here is my webpack.config.js
var path = require('path');
var SRC_DIR = path.join(__dirname, '/react-client/src');
var DIST_DIR = path.join(__dirname, '/react-client/dist');
module.exports = {
entry: `${SRC_DIR}/index.jsx`,
output: {
filename: 'bundle.js',
path: DIST_DIR
},
module : {
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
],
loaders : [
{
test : /\.jsx?/,
include : SRC_DIR,
loader : 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['env', 'react', 'es2015', 'stage-0']
}
}
]
}
};
Here is my starting file index.jsx as well:
import React, { Component } from 'react';
import Navbar from './components/Navbar.jsx';
import Login from './components/Login.jsx';
import SignUp from './components/SignUp.jsx';
import Search from './components/Search.jsx';
import ProductList from './components/ProductList.jsx';
import FavoriteList from './components/FavoriteList.jsx';
import { Route, Switch } from 'react-router-dom';
import {Container} from 'reactstrap';
import axios from 'axios';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
query : '',
products : [
{
name: 'Samsung - Galaxy J3 with 16GB Memory Cell Phone - Silver (AT&T)',
url: 'https://api.bestbuy.com/click/-/5887123/pdp',
price: 179.99,
image: 'https://img.bbystatic.com/BestBuy_US/images/products/5887/5887123_sd.jpg',
description: 'Android 7.0 Nougat4G LTE5" HD touch screenBluetooth'
},
{
name: 'Samsung - Book Cover for Samsung Galaxy Tab S2 8 - Black',
url: 'https://api.bestbuy.com/click/-/4346001/pdp',
price: 59.99,
image: 'https://img.bbystatic.com/BestBuy_US/images/products/4346/4346001_sd.jpg',
description: 'Compatible with Samsung Galaxy Tab S2 8; polyurethane material; auto on/off function; 3 viewing angles'
},
{
name: 'Samsung - Case for Samsung Galaxy S8 - Blue/clear',
url: 'https://api.bestbuy.com/click/-/5851701/pdp',
price: 19.99,
image: 'https://img.bbystatic.com/BestBuy_US/images/products/5851/5851701_sb.jpg',
description: 'Compatible with Samsung Galaxy S8'
}
],
favorites : []
}
}
handleQuery (event) {
event.preventDefault;
this.setState({
query : event.target.value
});
console.log(event.target.value);
//POST request for searching products
// axios.post('/search', {query : this.state.query}).then(function(response){
// this.setState = {products : response};
// })
}
render() {
return (
<div className="App">
<Navbar></Navbar>
<Container>
<Switch>
<Route path='/login' component={Login}/>
<Route path='/signup' component={SignUp}/>
<Route path='/' render = {(props) =>
<div>
<Search handleQuery = {this.handleQuery.bind(this)}></Search>
<ProductList products = {this.state.products}></ProductList>
</div>
}/>
<Route path='/favorites' render = {(props) =>
<FavoriteList favorites = {this.state.favorites}></FavoriteList>
}/>
</Switch>
</Container>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
Any help would be greatly appreciated
package.json
{
"name": "github-fetcher-fullstack-v2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"react-dev": "webpack -d --watch",
"server-dev": "nodemon server/index.js"
},
"author": "Beth Johnson",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.4.5",
"babel-loader": "^6.2.1",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.23.0",
"css-loader": "^0.28.11",
"react-hot-loader": "^4.1.2",
"webpack": "^2.7.0"
},
"dependencies": {
"angular": "^1.6.3",
"body-parser": "^1.17.2",
"bootstrap": "^4.1.0",
"express": "^4.15.0",
"jquery": "^3.1.1",
"mongoose": "^4.8.6",
"mysql": "^2.13.0",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"reactstrap": "^5.0.0"
}
}

Seems like Webpack config has a small problem and jsx files are not matched with appropriate loaders.
Try test: /\.jsx?$/, and see if it works.

You can easily fix by updating your config to process both .js and .jsx files:
module: {
loaders: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
}
You can add the following snippet to the webpack configuration object.
resolve: { extensions: [".jsx", ".js"] }

In your case, you might need to use js file that I recommend this config.
module:{
rules:[{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
test: /\.jsx?$/,
exclude: /node_modules/,
}, {
test: /\.s?css$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
}]
}
The config includes all loader for any file you might need, eg: js jsx css scss.

Related

ReactJS: Importing symlinked components error: Module parse failed: Unexpected token: You may need an appropriate loader to handle this file type

I'm writing a React component library which I want to use in other projects without much overhead ( bit, create-react-library, generact, etc. ) and without publishing. I want to use npm install ../shared_lib to add it to my project as a symlink in /node_modules. This command adds the symlink to project node_modules. In my shared_lib I just have a test to export default a <div></div>:
import React from 'react';
const TryTest = function() {
return (
<div>
TryTest
</div>
)
}
export default TryTest;
The problem I'm facing is the following error when I import the component into my working project:
import TryTest from 'shared_lib';
Error:
ERROR in ../shared_lib/src/index.js 6:4
Module parse failed: Unexpected token (6:4)
You may need an appropriate loader to handle this file type.
| const TryTest = function() {
| return (
> <div>
| TryTest
| </div>
# ./src/App.js 27:0-33 28:12-19
# ./src/index.js
# multi babel-polyfill ./src/index.js
If I import anything from shared_lib other than a file with jsx - for example, a string or a function, etc. - it works fine.
EDIT: the application webpack has resolve object's symlinks prop set to false:
resolve: {
symlinks: false
},
EDIT: After applying the solution in the answer below (https://stackoverflow.com/a/60980492/3006493), I later changed symlinks prop back to true. I didn't need to set it to false for the solution to work and render shared_lib components.
My app's loader:
{
test: /\.jsx?$/,
include: [
path.join( __dirname, 'src'), // app/src
fs.realpathSync(__dirname + '/node_modules/shared_lib'), // app/node_modules/shared_lib/dist/shared_lib.js
],
exclude: /node_modules/,
use: [ 'babel-loader' ]
}
EDIT: When I applied the solution in the answer below, the loader now looks like this:
{
test: /\.jsx?$/,
include: [
path.join( __dirname, 'src'), // app/src
fs.realpathSync(__dirname + '/node_modules/shared_lib'), // app/node_modules/shared_lib/dist/shared_lib.js
],
exclude: /node_modules/,
use: [ {
loader: 'babel-loader',
options: require("./package.json").babel
}
]
}
App's current .babelrc settings (I also tried removing .babelrc and including the presets in package.json with same result):
{
"presets": [ "#babel/preset-react", "#babel/preset-env"]
}
**EDIT: After applying the solution in the answer below, I ended up putting babel presets back into package.json.
"babel": {
"presets": [
"#babel/preset-react",
"#babel/preset-env"
]
},
I researched for a while to find a solution to this and apparently webpack has issues bundling symlinked react components? I am not using create-react-app.
So, I tried to bundle the shared_lib before importing it into the project, just to see what would happen. Here's the final webpack config (I tried other configurations as well):
const pkg = require('./package.json');
const path = require('path');
const buildPath = path.join( __dirname, 'dist' );
const clientPath = path.join( __dirname, 'src');
const depsPath = path.join( __dirname, 'node_modules');
const libraryName = pkg.name;
module.exports = [
'cheap-module-source-map'
].map( devtool => ({
bail: true,
mode: 'development',
entry: {
lib : [ 'babel-polyfill', path.join( clientPath, 'index.js' ) ]
},
output: {
path: buildPath,
filename: 'shared_lib.js',
libraryTarget: 'umd',
publicPath: '/dist/',
library: libraryName,
umdNamedDefine: true
},
// to avoid bundling react
externals: {
'react': {
commonjs: 'react',
commonjs2: 'react',
amd: 'React',
root: 'React'
}
},
module: {
rules: [
{
test: /\.jsx?$/,
include: [
clientPath
],
exclude: /node_modules/,
use: [ 'babel-loader' ],
},
]
},
devtool,
optimization: {
splitChunks: {
chunks: 'all',
},
}
}));
And the package.json for the shared_lib
{
"name": "shared_lib",
"version": "1.0.0",
"description": "",
"main": "dist/shared_lib.js",
"scripts": {
"clean": "rm -rf dist/",
"build": "$(npm bin)/webpack --config ./webpack.config.js",
"prepublish": "npm run clean && npm run build"
},
"author": "",
"license": "ISC",
"peerDependencies": {
"react": "^16.8.6"
},
"devDependencies": {
"react": "^16.8.6",
"#babel/core": "^7.9.0",
"#babel/preset-env": "^7.9.0",
"#babel/preset-react": "^7.9.4",
"babel-loader": "^8.1.0",
"babel-polyfill": "^6.26.0",
"webpack": "^4.42.1",
"webpack-cli": "^3.3.11"
},
"babel": {
"presets": [
"#babel/preset-react",
"#babel/preset-env"
]
}
}
The package is bundled without errors:
When I try to import the component in the same way:
import TryTest from 'shared_lib';
The console.log returns undefined.
The path to the library file in my app is fine, because if I erase everything in shared_lib/dist/shared_lib.js and just write export default 1 the console.log(TryTest) in my App.js will return 1.
I tried changing libraryTarget property in shared_lib/webpack.config to libraryTarget: 'commonjs'. The result of console.log(TryTest) becomes {shared_lib: undefined}.
Has anyone ever run into this?
I found what finally worked for me and rendered the symlinked shared_lib to the app.
This answer: https://github.com/webpack/webpack/issues/1643#issuecomment-552767686
Worked well rendering symlinked shared_lib components. I haven't discovered any drawbacks from using this solution, but it's the only one that worked so far.

Module parse failed using Webpack

Hi I am student developer. I facing an error like this
ERROR in ./src/index.js 5:16 Module parse failed: Unexpected token
(5:16) 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 | import App from
'../src/components/App' |
ReactDOM.render(,document.getElementById("app")); i 「wdm」: Failed to compile.
I am starting to learn webpack what it is but I do not have enough information about solving this. Could you help me at this issue to solve ?
package.json Dev Part :
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^8.0.6",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
}
My webconfig :
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.export = {
entry : './src/index.js',
output : {
path:path.join(__dirname,'/dist') ,
filename:'index_bundle.js'
},
module:{
rules : [{
test : /\.js$/,
exclude: /node_modules/,
use : {
loader : 'babel-loader'
}
}]
},
plugins: [
new HtmlWebpackPlugin({
template:'./src/index.html'
})
]
}
index.js
import React from 'react';
import ReactDOM from 'react-dom'
import App from '../src/components/App'
// Error is he
ReactDOM.render(<App />,document.getElementById("app"));
App.js:
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div>
<h1>Hello</h1>
</div>
);
}
}
export default App;
There are two mistakes in your webpack configuration, which is causing this issue.
There is a typo error. Change module.export to module.exports (This one drive me crazy man :P)
As #Muhammad mentioned, you need to mention webpack to compile the react. So, I have added '#babel/react' as presets for the babel-loader.
Below is the webpack that is working for me:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry : './src/index.js',
output : {
path:path.join(__dirname,'/dist') ,
filename:'index_bundle.js'
},
module:{
rules : [{
test : /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets: [
'#babel/react',
]
}
}]
},
plugins: [
new HtmlWebpackPlugin({
template:'./src/index.html'
})
]
}
Hope it helps :)
You need to tell webpack that you are compiling react. You need to update your rule as:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry : './src/index.js',
output : {
path:path.join(__dirname,'/dist') ,
filename:'index_bundle.js'
},
module:{
rules : [{
test: /\.js?$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: ["react"]
}
}]
},
plugins: [
new HtmlWebpackPlugin({
template:'./src/index.html'
})
]
}

React Material-ui SSR - Warning: Prop `d` did not match. Server: "M 0 0 h 24 v 24 H 0 Z" Client: "M0 0h24v24H0z"

I'm working on a React site with server-side rendering & Material-ui. Everything was working great including the mui JSS stuff.
Then I added an SVG icon from #material-ui/icons
Now, Edge & IE11 are complaining:
Warning: Prop d did not match. Server: "M 0 0 h 24 v 24 H 0 Z" Client: "M0 0h24v24H0z"
The warning indicates the server and client renderings don't match, but if I get the server rendering with curl it is correct and does NOT include the spaces shown in the IE/Edge console.
All other browsers are (of course) OK.
Has anyone else encountered SSR issues in MS browsers only?
This is as small as I can get an example. It's based on material-ui-master/examples/ssr with most stuff removed:
server.js:
import express from "express";
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from './App';
function renderFullPage(html) {
return `
<!doctype html>
<html>
<body>
<div id="root">${html}</div>
<script src="build/bundle.js"></script>
</body>
</html>
`;
}
function handleRender(req, res) {
// Render the component to a string.
const html = ReactDOMServer.renderToString(
<App />
);
res.send(renderFullPage(html));
}
const app = express();
app.use('/build', express.static('build'));
// This is fired every time the server-side receives a request.
app.use(handleRender);
const port = 3000;
app.listen(port);
client.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
class Main extends React.Component {
render() {
return <App />;
}
}
ReactDOM.hydrate(
<Main />
, document.querySelector('#root')
);
App.js:
import React from 'react';
import { Menu } from "#material-ui/icons";
export default class App extends React.Component {
render() {
return (
<Menu />
);
}
}
package.json:
{
"name": "ssr",
"version": "3.0.0",
"private": true,
"dependencies": {
"#babel/core": "latest",
"#babel/node": "latest",
"#babel/plugin-proposal-class-properties": "latest",
"#babel/preset-env": "^7.4.2",
"#babel/preset-react": "latest",
"#material-ui/core": "latest",
"#material-ui/icons": "^3.0.2",
"babel-loader": "next",
"express": "latest",
"fs": "0.0.1-security",
"net": "^1.0.2",
"nodemon": "latest",
"prop-types": "latest",
"react": "latest",
"react-dom": "latest",
"react-jss": "^8.1.0",
"webpack": "latest",
"webpack-cli": "latest"
},
"scripts": {
"start-server": "SET NODE_ENV=development& nodemon --inspect ./build/server.js",
"start": "webpack -w"
}
}
webpack.config.js:
const path = require('path');
const browserConfig = {
entry: './client.js',
node: {
fs: "empty"
},
mode: process.env.NODE_ENV || 'development',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
],
},
};
const serverConfig = {
entry: './server.js',
target: 'node',
node: {
fs: "empty"
},
mode: process.env.NODE_ENV || 'development',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'server.js',
publicPath: '/',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
],
},
};
module.exports = [browserConfig, serverConfig]
.babel.rc:
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["#babel/plugin-proposal-class-properties"]
}
I had a similar issue. This isn't a problem with SSR, but with conditional rendering in your JSX where the condition differs on the server and the client.
In my case, I rendered something based on a condition read from localStorage, which was only defined on the client. On server, it returned undefined, so what was rendered on the client and the server did not match.
The solution in my case was to conditionally render based on whether the component rendered on the client.
I wrote the following custom hook:
import {useEffect, useState} from "react";
export const useLoaded = () => {
const [loaded, setLoaded] = useState(false);
useEffect(() => setLoaded(true), []);
return loaded;
};
I use it as such:
// in the functional component's body
const loaded = useLoaded();
// in the JSX
{localCondition && loaded &&
<MyComponent />
}
With class components you'd use the componentDidMount lifecycle method and setState instead.
I've had the same problem ...did not match Server: ... Client: ... using NextJS (React) with an Express.js server (node server.js).
The solution was to render the component only if process.browser is true.
{
process.browser ?
<MyComponent /> :
null
}
So this does appear to be a bug in React. I logged an issue to the Material-ui project which resulted in this open issue in React:
https://github.com/facebook/react/issues/15187
The warning seems to be benign and with Edge moving over to Chromium, I'm not as concerned as I once was.

ReactJS Module build failed: SyntaxError: Unexpected token

I try to make ReactJS code but it fails to compile, I am with webpack-devserver.
My terminal return me :
ERROR in ./src/App.jsx Module build failed:
SyntaxError: Unexpected token
My webpack.config, App.js and package.json seems to be good to me.
I think I have make a well appeal to my modules.
Here my App.js :
import React, { Component } from 'react';
import './App.css';
import { BrowserRouter as Router, Route, Link} from 'react-router-dom';
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Route path='/' render={
()=> {
return (<h1> Welcome Home </h1> ) ;
}
}/>
</div>
</Router>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
Here my webpack.config.js :
const webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: {
app: __dirname +'/src/App.jsx'
},
output: {
path: __dirname + '/dist',
filename: 'app.bundle.js'
},
module: {
rules: {
test: /\.jsx$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: "es2015", "stage-0", "react"]
}
}
]
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true
}
}
]}
]},
(...)
};
My package.json :
devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-polyfill": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-es2015-node4": "^2.1.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"babel-register": "^6.26.0",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-router-dom": "^4.2.2",
}
Hi all I have resolve my problem by reset my code completly.
Basically, I had defaults on my webpack.config.js, littles severals errors causing crash, and I have reset my package.json and App.jsx. I have ensured the name of files and their extension follows exactly the content concerned (not js for jsx, and all).
I have create a modulate structure with component (App.jsx) and a render (index.jsx).
So here my new configuration :
webpack.config.js :
const webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: {
app: __dirname +'/src/index.jsx'
},
output: {
path: __dirname + '/dist',
filename: 'bundle.js'
},
module: {
rules: [ {
test: /\.js|jsx$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ["es2015", "stage-0", "react"]
}
}
]
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true
}
}
]}
]},
optimization : {
splitChunks: {
chunks: "async",
minSize: 3000,
minChunks: 1,
maxAsyncRequests: 5,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
},
devServer: {
contentBase: __dirname +'/dist'
}
};
my package.json :
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "./node_modules/.bin/nodemon ./server.js",
"build": "webpack-dev-server" ,
"watch": "webpack --watch",
"babelrc": "./node_modules/.bin/babelrc-to-install"
}
my App.jsx :
import React, { Component } from 'react';
import './App.css';
import {
BrowserRouter as Router,
Route,
Link,
NavLink,
Redirect,
Switch,
} from 'react-router-dom';
import User from './pages/user/user'
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Route path='/' render={
()=> {
return (<h1> Welcome Home </h1> ) ;
}
}/>
</div>
</Router>
);
}
}
export default App;
my index.jsx :
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
Works like a charm.
I have tried with the following code , it works fine , try changing ReactDOM.render to the following and let me know , if not working will check other faults
import React, { Component } from 'react';
import './App.css';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import { render } from 'react-dom';
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Route path='/' render={
() => {
return (<h1> Welcome Home </h1>);
}
} />
</div>
</Router>
);
}
}
render(<App />, document.getElementById('root'));

Cannot start react module

Getting the following exception when starting the npm.
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.module has an unknown property 'loaders'. These properties are valid:
object { exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, defaultRules?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp?, strictExportPresence?, strictThisContextOnImports? }
-> Options affecting the normal modules (NormalModuleFactory).
var path= require('path');
module.exports = {
entry : './script.jsx',
output : {
path : path.resolve(__dirname,''),
filename: 'transpiled.js'
},
module : {
loaders: [
{
test:/\.jsx?$/,
loaders:'babel-loader',
exclude : /node_modules/,
query : {
presets : ['es2015','react']
}
}
]
}
}
After the updations the code is running but react components are not getting rendered on the screen.
//Update
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test title</title>
</head>
<body>
<div id ="content">
<h1>This is the demo of your web page</h1>
</div>
<script src ="transpiled.js"></script>
</body>
</html>
//webpack config
var path= require('path');
module.exports = {
entry : './script.jsx',
output : {
path : path.resolve(__dirname,'react/index.html'),
filename: 'transpiled.js'
},
module : {
rules: [ // rules rules
{
test: /\.jsx?$/,
loaders: 'babel-loader',
//use:'babel-loader', // use here
exclude : /node_modules/,
query : {
presets : ['es2015','react']
}
}
]
}
}
//script.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class MyComponent extends React.Component {
render() {
return (
<h2>Hello World !!!</h2>
);
}
}
ReactDom.render(
<MyComponent/>,document.getElementById('content')
);
//package.json
{
"name": "reactjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"it": "webpack-dev-server --hot"
},
"author": "chetan",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"webpack": "^4.5.0",
"webpack-cli": "^2.0.14",
"webpack-dev-middleware": "^3.1.2",
"webpack-dev-server": "^3.1.3",
"webpack-hot-middleware": "^2.21.2"
},
"dependencies": {
"react": "^16.3.1",
"react-dom": "^16.3.1",
"webpack-sources": "^1.1.0"
}
}
You need to replace keyword loaders to keyword rules. And in each rules object replace loaders to keyword use.
module.exports = {
entry : './script.jsx',
output : {
path : path.resolve(__dirname,''),
filename: 'transpiled.js'
},
module : {
rules: [ // rules rules
{
test:/\.jsx?$/,
use:'babel-loader', // use here
exclude : /node_modules/,
query : {
presets : ['es2015','react']
}
}
]
}
}
Edit
Now your component not rendered on the screen because output.path in webpack config incorrect. It should be like this:
output : {
path : path.resolve(__dirname),
filename: 'transpiled.js'
}
Because script tag in your html reference in root of the project:
<script src="transpiled.js"></script>
Your webpack.config file is in the wrong format
var path = require('path');
module.exports = {
entry: './script.jsx',
output: {
path: path.resolve(__dirname, ''),
filename: 'transpiled.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
loaders: 'babel-loader',
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
// your preset
]
}
}
]
}
]
}
}
See more here

Resources