Webpack build React.createClass is not a function - javascript

I have a ReactJS application with webpack module builder, following is the configuration in my webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: {
app : './src/scripts/app.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'public')
},
context: __dirname,
resolve: {
extensions: ['.js', '.jsx', '.json', '*']
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
options: {
presets: ['react', 'es2015']
}
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader'
]
}
]
}
};
I have following code in my app.js
import React from 'react';
import ReactDOM from 'react-dom';
var MainApp = React.createClass({
render: function(){
return (
<div>
<div>Header component</div>
<div>Boady component</div>
</div>
);
}
});
ReactDOM.render(
<MainApp />,
document.getElementById('container')
);
Now after running the server, when I load my page in browser getting following error:
Uncaught TypeError: _react2.default.createClass is not a function
Attaching screenshot of the error message:
I would like to know more details on this issue, many thanks for the help.

You need to install this npm extension:
npm install create-react-class --save
And then use this code:
var createReactClass = require('create-react-class');
var MainApp = createReactClass({
render: function(){
return (
<div>
<div>Header component</div>
<div>Boady component</div>
</div>
);
}
});
}

Related

Failed to resolve import "React" in npm package and webpack 5

I am developing a npm package and use there webpack 5.
This is my config
const path = require('path') // resolve path
module.exports = {
mode: 'development',
resolve: {
extensions: ['.js', '.jsx'], // we can import without typing '.js or .jsx'
},
entry: {
index: path.join(__dirname, 'src/index.jsx'),
},
output: {
path: path.resolve(__dirname, './dist'),
filename: 'index.js', // for production use [contenthash], for developement use [hash]
library: {
type: 'module',
},
environment: { module: true },
},
experiments: {
outputModule: true,
},
devtool: 'eval',
module: {
rules: [
{
test: /\.(css|scss|sass)$/,
use: [
{
loader: 'style-loader', // creates style nodes from JS strings
},
{
loader: 'css-loader', // translates CSS into CommonJS
},
{
loader: 'sass-loader', // compiles Sass to CSS
},
],
},
{
test: /\.(js|jsx)$/,
exclude: /nodeModules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.(png|svg|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
},
],
},
{
test: /.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
exclude:
/images/ /* dont want svg images from image folder to be included */,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'fonts/',
name: '[name][hash].[ext]',
},
},
],
},
],
},
externals: {
react: 'React',
'react-dom': 'ReactDOM',
},
plugins: [],
}
When I want to import components from this library I get this error:
Failed to resolve import "React" from "..my-package/dist/index.js". Does the file exist?
I think this has something to do with externals react and react-dom. But when I remove the externals from webpack config I get the error that react should be only installed once when using react hooks.
In my main application I am using vite for bundeling but I tried it also with create-react-app and have the same problem.
My Library Component:
import React, { useState } from 'react'
const App = () => {
const [counter, setCounter] = useState(0)
return <div>{counter}</div>
}
export default App
This is how I am using it with npm-link:
import React from "react";
import Test from "my-package";
const App = () => {
return <Test />;
};
export default App;
Here is the repo with the code https://github.com/guitar9/webpack-bug

Webpack-dev-server is very slow?

Webpack-dev-server is so slow in rebuilding my simple app, my app is just one component, index.js
This is config.webpack.js file:
const path = require('path');
const HTMLplugin = require('html-webpack-plugin');
const htmlplugin = new HTMLplugin({
template: './public/index.html'
});
const rules = [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader']
}
];
module.exports = {
entry: path.join(__dirname, 'src', 'index.js'),
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './build')
},
module: { rules },
plugins: [htmlplugin]
}
index.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App'
const App = () => {
return (
<p>Hello World</p>
)
}
ReactDOM.render(<App />, document.getElementById('root'));
I am new to webpack and i can't really understand why it is that slow although i only have one simple component in my project, i don't know if i should show my package.json file or not as i think it is not related to my problem
What am i doing wrong??

Error while using webpack to compile jsx and js

I am trying to use koajs and reactjs to make a boilerplate application, to use later as a starting point for projects.
I am trying to use webpack as a means to compile my react jsx files, but I am getting this error:
ERROR in ./src/js/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'));
const path = require('path');
module.exports = {
mode: "development",
entry: './src/js/index.js',
loader: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env", "#babel/preset-react"]
}
}
}
]
},
output: {
path: path.join(__dirname, '/src/js'),
filename: 'index_bundle.js'
}
}
index.js:
import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
ReactDOM.render(<App />, document.getElementById('app'));
module.exports = {
mode: "development",
entry: './src/js/index.js',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env", "#babel/preset-react"]
}
}
}
]
},
output: {
path: path.join(__dirname, '/src/js'),
filename: 'index_bundle.js'
}
}

HMR with Electron and React?

I've followed the following guides:
https://webpack.js.org/guides/hmr-react/
http://gaearon.github.io/react-hot-loader/getstarted/
https://github.com/wkwiatek/react-hot-loader-minimal-boilerplate
But I can't seem to make HMR work for Electron. These are logs I get when I apply some changes:
[WDS] App updated. Recompiling...
[WDS] App hot update...
[HMR] Checking for updates on the server...
[HMR] Cannot find update. Need to do a full reload!
[HMR] (Probably because of restarting the webpack-dev-server)
[HMR] Waiting for update signal from WDS...
[WDS] Hot Module Replacement enabled.
This is my webpack.config.js:
const webpack = require('webpack')
const { join, resolve } = require('path')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
context: resolve(__dirname, 'app'),
entry: [
'babel-polyfill',
'react-hot-loader/patch',
'./index.tsx'
],
output: {
filename: './bundle.js',
path: resolve(__dirname, 'dist')
},
module: {
rules: [{
test: /\.(js|ts|tsx)$/,
use: 'babel-loader',
exclude: /node_modules/
}, {
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/
}, {
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [{
loader: 'css-loader'
}, {
loader: 'sass-loader'
}
]
}),
exclude: /node_modules/
}]
},
target: 'electron',
resolve: {
extensions: ['.tsx', '.ts', '.js', '.jsx', 'scss']
},
devtool: 'source-map',
plugins: [
new ExtractTextPlugin('bundle.css')
]
}
This is my start script:
"watch": "./node_modules/.bin/webpack-dev-server --hot --history-api-fallback"
This is my root component:
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import { Provider, Store } from 'react-redux'
import App from './App'
import reducer from './reducers'
import configureStore from './store/configureStore'
import './stylesheets/index.scss'
const store: Store<any> = configureStore()
const render = (Component) => {
ReactDOM.render(
<AppContainer>
<Provider store={store}>
<Component/>
</Provider>
</AppContainer>,
document.getElementById('root')
)
}
render(App)
if (module['hot']) {
module['hot'].accept('./App', () => {
render(App)
})
}
This is my .babelrc config:
{
"presets": [
["es2015", {"modules": false}],
"react"
],
"plugins": [
"react-hot-loader/babel"
]
}
Also my index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Markers - Notes for students</title>
<link href="http://localhost:8080/bundle.css" rel="stylesheet"/>
</head>
<body>
<div id="root"></div>
<script src="http://localhost:8080/bundle.js"></script>
</body>
</html>
I don't know if it has something to do but I'm using typescript. Any help is welcome. Thanks!

Webpack SCSS to CSS extraction not working

I am trying to extract SCSS to CSS on my react.js app using webpack plugin: extract-text-webpack-plugin. I am not getting any errors but i can't see any style on my page when i compile. In the following code i am simply trying to change the color of hello world rendered on the screen from black to red. Here are my files:
webpack.config.js
var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
devtool: 'inline-source-map',
entry: [
'webpack-dev-server/client?http://127.0.0.1:8080/',
'webpack/hot/only-dev-server',
'./src/index.js',
'./sass/styles.scss'
],
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
resolve: {
modules: ['node_modules', 'src'],
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ['react-hot-loader', 'babel-loader']
},
{ // regular css files
test: /\.css$/,
loader: ExtractTextPlugin.extract({
loader: 'css-loader?importLoaders=1',
}),
},
{ // sass / scss loader for webpack
test: /\.(sass|scss)$/,
loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new ExtractTextPlugin("styles.css")
]
};
styles.scss
$color : red;
.hello{
font-color: $color;
text-align: center;
}
app.js
import React from 'react';
export default class App extends React.Component {
render() {
return (
<div>
<h1 className = "hello">Hello World</h1>
</div>);
}
}
index.js
import React from 'react';
import { render } from 'react-dom';
import App from './components/app';
render ( <App />, document.getElementById('app'));
What i'm I missing?
you're missing style-loader from your loader chain.
from the sass-loader docs:
Chain the sass-loader with the css-loader and the style-loader to immediately apply all styles to the DOM.
// webpack.config.js
module.exports = {
...
module: {
rules: [{
test: /\.scss$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}]
}]
}
};
you need import styles.scss in code index.js
import 'yourlink/styles.scss'

Categories