React not rendering custom elements (babel + webpack) - reactjs

I created an app using create-react-app and started to use webpack and babel.
What I get from this code is that I cannot render my components (example, <App />).
I can only render elements like h1 or h2, even if I import App in index.js (and don't use it), I cannot see anything.
I run with npm run dev-server.
webpack.config.js:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['#babel/react']
}
}
]
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
devtool: 'cheap-module-eval-source-map',
devServer: {
contentBase: path.join(__dirname, 'public')
}
};
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './style.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
App.js:
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div className="mainContainer">
<h1>Test h1</h1>
<h2>Test h2</h2>
<p>Test p</p>
</div>
);
}
}
export default App;
package.json:
{
"name": "smartpharma-front",
"version": "0.0.1",
"private": true,
"dependencies": {
"axios": "^0.19.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-scripts": "^3.3.0"
},
"scripts": {
"start": "webpack --mode=development",
"build": "webpack --mode=production",
"dev-server": "webpack-dev-server",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"engines": {
"node": "13.3.0",
"npm": "6.13.1"
},
"devDependencies": {
"#babel/core": "^7.7.7",
"#babel/preset-env": "^7.7.7",
"#babel/preset-react": "^7.7.4",
"babel-loader": "^8.0.6",
"css-loader": "^3.4.0",
"style-loader": "^1.1.1",
"webpack": "^4.41.4",
"webpack-cli": "^3.3.10"
},
"description": "SmartPharma Frontend",
"main": "webpack.config.js",
"repository": {
"type": "git",
"url": "git+https://github.com/vfeder6/smartpharma-front.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/vfeder6/smartpharma-front/issues"
},
"homepage": "https://github.com/vfeder6/smartpharma-front#readme"
}

Related

Webpack Does Not Recognise Babel Loader Even when babel loader is installed

I have webpack and babel loader installed, however, webpack is unable to recognise that Babel Loader is installed:
I installed babel loader and the presets using the following command: npm install #babel/core babel-loader #babel/preset-react --save-dev
Here is my
webpack.config.js:
const path = require('path')
const config = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'main.js',
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
options: {
presets: ['#babel/preset-react'],
},
},
],
},
}
module.exports = config
and package.json:
{
"name": "webpack",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.3.0",
"#testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "webpack --mode=development",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/core": "^7.18.6",
"#babel/preset-react": "^7.18.6",
"babel-loader": "^8.2.5",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"install": "^0.13.0",
"npm": "^8.13.2",
"webpack": "^5.73.0",
"webpack-cli": "^4.10.0"
}
}
Your Webpacks Babel module rule object has a wrong structure. Please, follow the Webpack official docs and wrap your 'loader' and 'options' properties in a 'use'.
Wrong rules:
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
options: {
presets: ['#babel/preset-react'],
},
},
],
},
Correct rules:
module: {
rules: [
{
test: /\.m?js$/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-react']
}
}
}
]
}

Problem using a NPM Package builded with Rollup

I am creating a npm package with react components, providers, and other utilities. The idea is use this npm package in other projects. I configured rollup to create the builds but when I try to use it in another project I got a "React is not defined" error.
Here is my code and the error in detail:
package.json:
{
"name": "myapp",
"version": "0.1.14",
"description": "Npm package.",
"main": "lib/index.cjs.js",
"module": "lib/index.esm.js",
"files": [
"dist",
"README.md"
],
"scripts": {
"start": "react-scripts start",
"build": "npx rollup -c",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": ""
},
"author": "",
"license": "ISC",
"dependencies": {
"#babel/polyfill": "^7.12.1",
"#fluentui/react": "8.52.2",
"#rjsf/core": "4.2.0",
"#rjsf/fluent-ui": "4.2.0",
"#types/node": "^17.0.21",
"#types/react": "^17.0.40",
"#types/react-dom": "^17.0.13",
"axios": "^0.25.0",
"office-ui-fabric-core": "^11.0.0",
"react-query": "^3.34.19",
"react-simple-resizer": "^2.1.0"
},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
"#fluentui/react": "8.52.2"
},
"devDependencies": {
"#babel/cli": "^7.17.0",
"#babel/core": "^7.17.0",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.16.7",
"#fluentui/example-data": "^8.4.0",
"#rollup/plugin-babel": "^5.3.0",
"#rollup/plugin-commonjs": "^21.0.1",
"#rollup/plugin-node-resolve": "^13.1.3",
"#rollup/plugin-replace": "^4.0.0",
"#rollup/plugin-typescript": "^8.3.1",
"react-scripts": "^5.0.0",
"rollup": "^2.67.1",
"rollup-plugin-import-css": "^3.0.3",
"rollup-plugin-includepaths": "^0.2.4",
"rollup-plugin-peer-deps-external": "^2.2.4",
"rollup-plugin-terser": "^7.0.2",
"typescript": "^4.6.2",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
rollup.config.js:
import babel from "#rollup/plugin-babel";
import resolve from "#rollup/plugin-node-resolve";
import commonjs from "#rollup/plugin-commonjs";
import includePaths from "rollup-plugin-includepaths";
import peerDepsExternal from "rollup-plugin-peer-deps-external";
import { terser } from "rollup-plugin-terser";
import pkg from "./package.json";
import typescript from "#rollup/plugin-typescript";
import css from "rollup-plugin-import-css";
import replace from "#rollup/plugin-replace";
const outputs = [
{
file: pkg.main,
format: "umd",
},
{
file: pkg.module,
format: "es",
}
]
const external = [
...Object.keys(pkg.peerDependencies || {})
].map(name => RegExp(`^${name}($|/)`))
const config = outputs.map(({ file, format }) => ({
input: "src/lib/index.js",
output: {
file,
format,
name: "ReactPackage",
globals: {
react: "React",
"react-dom": "ReactDOM",
"#fluentui/react": "FluentUI",
}
},
external,
plugins: [
typescript(),
peerDepsExternal(),
includePaths({
include: {},
paths: ["src/lib"],
external: Object.keys(pkg.dependencies),
extensions: ['.js', '.json', '.html', '.tsx', '.ts']
}),
css(),
babel({
babelHelpers: "bundled",
exclude: "node_modules/**",
configFile: "./babel.config.rollup.js",
}),
resolve({
browser: true
}),
commonjs(),
terser(),
replace({
preventAssignment: true,
'process.env.NODE_ENV': JSON.stringify('production')
})
],
}));
export default config;
Babel:
const pkg = require('./package.json');
module.exports = {
presets: [
[
'#babel/preset-env',
{
modules: false,
targets: pkg.browserslist.production,
},
],
[
'#babel/preset-react',
{
"runtime": "automatic"
}
]
],
ignore: ['node_modules/**'],
};
The provider that I am trying to use but I get an "React is not defined" error:
Provider.ts:
import PContext from "../contexts/pContext";
import { QueryClient, QueryClientProvider } from "react-query";
import React, { useState } from "react";
const queryClient = new QueryClient();
const PProvider = ({ children, url }) => {
const [active, setActive] = useState(null);
return (
<PContext.Provider
value={{
url,
active,
setActive
}}
>
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
</PContext.Provider>
);
};
export default PProvider;

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. (webpack)

Im trying to configure webpack for React.
But when i ran "npm run start" i got this error in VSC console:
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 "./components/App";
|
> ReactDOM.render(<App />, document.getElementById("app"));
|
webpack.config.js:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.export = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
},
resolve: {
extensions: [".js", ".jsx"],
},
module: {
rules: [
{
test: /\.js|\.jsx$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.html$/,
use: [{ loader: "html-loader" }],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html",
filename: "./index.html",
}),
],
devServer: {
static: path.join(__dirname, "dist"),
compress: true,
port: 3000,
},
};
Index.js:
import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
ReactDOM.render(<App />, document.getElementById("app"));
Package.json:
{
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"name": "curso-webpack-react",
"description": "",
"version": "1.0.0",
"main": "index.js",
"devDependencies": {
"#babel/core": "^7.15.5",
"#babel/preset-env": "^7.15.6",
"#babel/preset-react": "^7.14.5",
"babel-loader": "^8.2.2",
"html-loader": "^2.1.2",
"html-webpack-plugin": "^5.3.2",
"prettier": "2.4.1",
"webpack": "^5.53.0",
"webpack-cli": "^4.8.0",
"webpack-dev-server": "^4.2.1"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server",
"build": "webpack --mode production"
},
"repository": {
"type": "git",
"url": "git+https://github.com/platzi/curso-webpack-react.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/platzi/curso-webpack-react/issues"
},
"homepage": "https://github.com/platzi/curso-webpack-react#readme"
}
.babelrc:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
I don't know what to try anymore.
Iv tried to change test: /\.(.js|jsx)$/, to test: /\.js$|jsx/, or test: /\.js|\.jsx$/, but no results.
Iv also tried others solutions to the same problems that iv saw in others stackoverflow publications, but no results tho.

How to make npm module written in es6 point to source when opening to declaration

I have published a npm module written in ES6. I have used Babel to transpile it to ES5 and webpack to bundle it.
Now when I import the module in my React app and when I go to the declaration, ES5 code is opened.
module.exports = (function (e) {
var t = {};
function r(n) {}
...
I want to show the ES6 code when opening declaration in an IDE, not the ES5 doe.
import React from 'react';
export class RerenderTracker extends React.Component {
componentWillUnmount() {}
...
Here is my package.json
{
"name": "rerender-tracker",
"version": "1.0.10",
"description": "Component for tracking react rerenders",
"main": "./build/index.js",
"scripts": {
"build": "webpack --mode production",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://github.com/mtroskot/rerender-tracker.git"
},
"keywords": [
"react",
"render",
"rerender",
"tracker"
],
"author": "Marko Troskot",
"license": "MIT",
"bugs": {
"url": "https://github.com/mtroskot/rerender-tracker/issues"
},
"homepage": "https://github.com/mtroskot/rerender-tracker#readme",
"peerDependencies": {
"react": ">=16"
},
"dependencies": {
"react": "^16.13.1"
},
"devDependencies": {
"#babel/core": "^7.9.6",
"#babel/plugin-proposal-class-properties": "^7.8.3",
"#babel/preset-env": "^7.9.6",
"#babel/preset-react": "^7.9.4",
"babel-loader": "^8.1.0",
"babel-runtime": "^6.26.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11"
}
}
my .babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["#babel/plugin-proposal-class-properties"]
}
my webpack.config.js
var path= require("path");
module.exports = {
entry:"./src/index.js",
output:{
path:path.resolve("build"),
filename:"index.js",
libraryTarget:"commonjs2"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
externals:{
react:"react"
}
};
Note
This is my first npm module so if there is something wrong in the configs or doesn't follow best practices, please let me know.

How can I render a react application compiled in a bundle.js?

So I have a React application that was compiled into a bundle.js file. The index.tsx file of the React application shows that the App component will be rendered in a DOM element with ID "scheduleSitesGrid2" as showed on this picture:
I have been able to bundle this react app and host the bundle on Azure Storage. In fact, if I create a simple HTML file that only contains a div and a script with a src pointing to the azure url, I am able to see the bundle.js in Chrome DevTools:
When I open the dummy index.html, I cannot see the React App component. There are no errors on the console as well.
I also tried to add breakpoints in the App component and they are triggered when the page loads. I am just wondering where the index.html page is blank even if I inserted a div with the valid ID.
Here is my App.tsx file:
import React, {Component} from 'react';
import '#progress/kendo-theme-default/dist/all.css';
import './App.css';
import jobs from './jobs.json';
import { Grid, GridColumn } from '#progress/kendo-react-grid';
import { DropDownListChangeEvent } from '#progress/kendo-react-dropdowns';
import EditIconComponent from "./components/editicon.component";
import UploadIconComponent from "./components/uploadicon.component";
export default class App extends Component {
handleDropDownChange = (e: DropDownListChangeEvent) => {
this.setState({
dropdownlistCategory: e.target.value.CategoryID
});
}
state = { skip: 0, take: 5 }
pageChange = (event: any) => {
this.setState({
skip: event.page.skip,
take: event.page.take
});
}
render() {
return (
<div className="App">
<Grid
resizable={true}
pageable={true}
skip={this.state.skip}
take={this.state.take}
total={jobs.length}
onPageChange={this.pageChange}
data={jobs.slice(this.state.skip, this.state.take + this.state.skip)}>
<GridColumn field="null" title=" " cell={EditIconComponent} resizable={false} width="50px"/>
<GridColumn field="null" title=" " cell={UploadIconComponent} resizable={false} width="50px"/>
<GridColumn field="technology" title="Technology" />
<GridColumn field="marketcost" title="Market/Cost"/>
<GridColumn field="num" title="Job #" />
<GridColumn field="locationCode" title="Location Code" />
<GridColumn field="siteName" title="Site Name" />
<GridColumn field="pin" title="PIN" />
<GridColumn field="status" title="Job Status" />
</Grid>
</div>
);
}
}
Here is the entire index.tsx file:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('scheduleSitesGrid2'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: .....
serviceWorker.unregister();
And here is my package.json
{
"name": "kendo-grid-test",
"version": "0.1.0",
"private": true,
"dependencies": {
"#progress/kendo-data-query": "^1.5.2",
"#progress/kendo-drawing": "^1.6.0",
"#progress/kendo-react-dateinputs": "^3.6.0",
"#progress/kendo-react-dialogs": "^3.6.0",
"#progress/kendo-react-dropdowns": "^3.6.0",
"#progress/kendo-react-grid": "^3.6.0",
"#progress/kendo-react-inputs": "^3.6.0",
"#progress/kendo-react-intl": "^3.6.0",
"#progress/kendo-theme-default": "^4.5.2",
"#types/jest": "24.0.19",
"#types/node": "12.11.6",
"#types/react-dom": "16.9.2",
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-scripts": "3.2.0"
},
"scripts": {
"start": "react-scripts start",
"build": "./node_modules/.bin/webpack",
"pack": "webpack --config webpack.config.js",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/core": "^7.6.4",
"#babel/preset-env": "^7.6.3",
"#babel/preset-react": "^7.6.3",
"#types/react": "^16.9.9",
"babel-loader": "^8.0.6",
"glob": "^7.1.5",
"source-map-loader": "^0.2.4",
"ts-loader": "^6.2.1",
"typescript": "^3.6.4",
"uglifyjs-webpack-plugin": "^2.2.0",
"webpack-cli": "^3.3.10"
}
}
UPDATE
When I created the bundle, public/index.html was an empty file. If I add some basic html code and include the div with id scheduleSitesGrid2, I see that App component is working fine:
Thank you!
I found the issue. I had an issue in my Webpack.config.js file. I set the entry to src/App.tsx, but I changed it to src/index.tsx.
Thank you so much everyone for your help!
Have a good day
Here is my Webpack.config if someone needs it:
"use strict"
const path = require('path');
module.exports = {
entry: './src/index.tsx',
output: {
filename: "bundle.js",
path: path.resolve(__dirname, 'dist')
},
devServer: {
publicPath: "/",
contentBase: "./public",
hot: true
},
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
devtool: "inline-source-map",
module: {
rules: [{
test: /\.(ts|tsx)$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}]
}
};

Resources