Webpack React library to global variable in window - reactjs

I use webpack to build React components.
Here is the JSX file:
// index.js
var React = require('react');
var ReactDOM = require('react-dom');
var renderHelloComponnet = function(id) {
ReactDOM.render(
<h1>Hello, World!</h1>,
document.getElementById(id)
);
}
Then, I want to call the function renderHelloComponnet in html
I have the config file for webpack:
module.exports = {
entry: {
index: './src/index.js'
},
output: {
path: __dirname + '/build',
filename: '[name].bundle.js',
libraryTarget: "var",
library: ["ABC"],
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: { presets:['react'] }
}
]
}
}
However I can't render my component in html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script type="text/javascript" src="./build/index.bundle.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/javascript">
ABC.renderHelloComponnet('example');
</script>
</body>
</html>
I get the error: TypeError: ABC.renderHelloComponnet is not a function

What you export in your module.exports is what you get in your library var. So if in your index.js you export renderHelloComponent:
module.exports = renderHelloComponent;
then in your ABC var you'll get the function:
<script type="text/javascript">
ABC('example');
</script>
If you want your library var to actually have the renderHelloComponent method you can export an object with this function inside:
module.exports = {
renderHelloComponent: renderHelloComponent
}
Then you will be able to do this:
<script>
ABC.renderHelloComponent('example');
</script>

Related

Uncaught Error: Target container is not a DOM element. in React

I encountered this error when trying to set up my React app. I have looked at other people's solution, but didn't seem to find the solution that works for me.
I normally just do create-react-app, but this time I try to configure webpack and I'm not sure what went wrong here.
my index.js and App.js files are both in the src folder and my index.html is inside the dist folder
THANK YOU FOR YOUR HELP
my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>High Five</title>
</head>
<body>
<div id="app"></div>
<script src="bundle.js"></script>
</body>
</html>
my webpack.config.js
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const config = {
entry: ["react-hot-loader/patch", "./src/index.js"],
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: "babel-loader",
exclude: /node_modules/,
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
{
test: /\.scss$/,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
},
{
test: /\.png$/,
use: [
{
loader: "url-loader",
options: {
mimetype: "image/png",
},
},
],
},
{
test: /\.svg$/,
use: "file-loader",
},
],
},
resolve: {
extensions: [".js", ".jsx"],
alias: {
"react-dom": "#hot-loader/react-dom",
},
},
devServer: {
contentBase: "./dist",
},
plugins: [
new HtmlWebpackPlugin({
appMountId: "app",
filename: "index.html",
}),
new MiniCssExtractPlugin(),
],
};
module.exports = config;
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import "./styles.css";
ReactDOM.render(<App />, document.getElementById("app"));
App.js
import React, { Component } from "react";
import { hot } from "react-hot-loader/root";
class App extends Component {
render() {
return (
<div>
<h1>Hello React</h1>
</div>
);
}
}
export default hot(App);

React element is not rendering / React Setup Issue

I am trying to learn to react, after spending two days on setting up webpack and babel. Finally, I am trying to run some sample code. I am trying to print some strings from my react element, and unable to get this element working.
I do get the "Hello World" which is from the HTML, and no compilation errors for react, so I can validate client-server setup is working well.
However, the react element is not rendered.
Following is three file setup.
components/homepage.js
"use strict";
var React = require('react');
var Home = React.createClass({
render: function () {
return (
<div className="jumbotron">
<h1>PluralSight Adminstrator</h1>
<p>React, React Router, and Flux for ultra responsive website</p>
</div>
);
}
});
module.exports = Home;
And index.js
const jquery = $ = require('jquery');
const Home = require('./components/homepage');
const ReactDOM = require('react-dom');
ReactDOM.render(<Home/>, document.getElementById('app'));
And index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="index.js"></script>
</head>
<body>
<div id="app"></div>
Hello World.:)
</body>
</html>
webpack.config.dev.js
const webpack = require('webpack');
const path = require('path');
module.exports = {
debug: true,
devtool: 'inline-source-map',
noInfo: false,
entry: [
'eventsource-polyfill', // necessary for hot reloading with IE
'webpack-hot-middleware/client?reload=true', //note that it reloads the page if hot module reloading fails.
path.resolve(__dirname, 'src/index')
],
target: 'web',
output: {
path: __dirname + '/dist', // Note: Physical files are only output by the production build task `npm run build`.
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: path.resolve(__dirname, 'src')
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
{test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']},
{test: /(\.css)$/, loaders: ['style', 'css']},
{test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
{test: /\.(woff|woff2)$/, loader: 'url?prefix=font/&limit=5000'},
{test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
{test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'}
]
}
};
The following code should work (replace the home component code):
var Home = class Home extends React.Component {
render() {
return (
<div className="jumbotron">
<h1>PluralSight Adminstrator</h1>
<p>React, React Router, and Flux for ultra responsive website</p>
</div>
);
}
}
According to docs, if you want to use create-react-class then you need to install the package using NPM and require it as shown below:
var createReactClass = require('create-react-class');
The compiler might not show the error, but your browser's console must be showing some error.
Ref fiddle: https://jsfiddle.net/69z2wepo/194263/

ReactDom.render not rendering the html content

I am able to transpile the jsx code but in browser its not loading anything. I am using babel and webpack too.
app.jsx
const ReactDom = require('react-dom');
const React = require('react');
ReactDOM.render(
<h1>Hello World</h1>,
document.getElementById("root")
);
index.html
<html>
<head>
</head>
<body>
<div id="root"></div>
<script type="text/javascript" src="./js/bundle.js">
</script>
</body>
</html>
webpack.config.js
module.exports = {
entry: './jsx/app.jsx',
output: {
path: __dirname + '/js/',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
loaders: ['babel-loader']
}
]
}
}
bundle.js
------
------
(function(module, exports, __webpack_require__) {
const ReactDom = __webpack_require__(15);
const React = __webpack_require__(4);
ReactDOM.render(React.createElement(
'h1',
{ htmlFor: 'yes' },
'Hello World'
), document.getElementById("root"));
}),
------
------
When I looked into html page source it showing linked to bundle.js in script tag but page is blank.
You can check my complete project on Github complete code
Steps I am following to run
npm run build
static (I am using node-static)
then loading index.html in browser but page is blank.
You have a typo - ReactDOM should be ReactDom. The error that is shown in the console is Uncaught ReferenceError: ReactDOM is not defined.

ReactJs AdminLTE Dashboard

I am new in ReactJS. I want to use ReactJS-AdminLTE in my project. Can anybody tell how to use it with step by step process.
Steps I followed
1) I set Reactjs environment using https://www.tutorialspoint.com/reactjs/ tutorial
2) Then I install ReactJS-AdminLTE using command npm install adminlte-reactjs
My webpack.config file is
var path=require('path');
var config = {
entry: './main.js',
output: {
path: path.join(__dirname, "./"),
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
App.jsx
import React from 'react';
import reactjsAdminlte from 'adminlte-reactjs';
class App extends React.Component {
render() {
return (
<Box
width = 3
border = true
content = 'The body of the box'
theme = 'box-primary'
title = 'Collapsable'
collapsed = true
boxTools = ['collapse']
/>
);
}
}
export default App;
Index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src = "index.js"></script>
</body>
</html>
But result is not displaing.
Are you using ReactDOM to render your app component to the HTML?
import ReactDOM from 'react-dom';
ReactDOM.render(
<App />,
document.getElementById('app')
);

Why is React Chunking not working?

I am trying to chunk my react app using webpack, but nothing loads and it says vendor.js says 0 bytes. What am I doing wrong? I think there is something wrong in my index.html. vendor.js and index.js are both located in the src folder. I've already tried following this, but no luck https://github.com/webpack/webpack/issues/368
Webpack
var webpack = require('webpack');
module.exports = {
entry: {
app: './src/index.js',
vendor: './src/vendor.js'
},
output: {
path: __dirname,
publicPath: '/',
filename: '[name].js'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin('vendor.js')
],
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
};
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/style/style.css">
</head>
<body>
<div id="app"></div>
</body>
<script src="/bundle.js"></script>
</html>
You should add all of your common dependencies into vendor.js via import,
e.g jquery, lodash, post-css, jss or any others which you are using.
since you have not done that may be because of that your vendor.js file is of size 0 bytes.
Change your CommonsChunkPlugin to
new webpack.optimize.CommonsChunkPlugin({
name : 'vendor',
}),
Also you need to change your index.html
because in your webpack config you have
output: {
path: __dirname,
publicPath: '/',
filename: '[name].js'
},
Here
filename: '[name].js'
means files will be generated by webpack based on entry names as app.js and vendor.js
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/style/style.css">
</head>
<body>
<div id="app"></div>
</body>
<script src="/vendor.js"></script>
<script src="/app.js"></script>
</html>
change new webpack.optimize.CommonsChunkPlugin('vendor.js') to
new webpack.optimize.CommonsChunkPlugin('vendor','vendor.js', Infinity)
or better be new webpack.optimize.CommonsChunkPlugin('vendor','vendor.[chunkhash].js', Infinity)
I would recommend migrating to Webpack 2. Refer migrating guide

Resources