Deploying react app with webpack server - javascript

I am a beginner in ReactJS and was just exploring it and trying to configure it with Webpack and Babel when I experienced an error when I run the application using npm start.
Following are some of files:-
package.json
{
"name": "reactstarter",
"version": "1.0.0",
"description": "A basic React application to explore its state and beauty",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"keywords": [
"reactjs"
],
"author": "user1705",
"license": "MIT",
"dependencies": {
"debug-log": "^1.0.1",
"react": "^15.3.2",
"react-dom": "^15.3.2"
},
"devDependencies": {
"webpack": "^1.13.2"
}
}
There are two directories src directory and dist directory inside the root folder.
File: src/index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src = "/app/bundle.js"></script>
</body>
</html>
File:- src/app/App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
Hello World!!!
</div>
);
}
}
export default App;
File:- src/app/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
And webpack.config.js:-
var webpack= require(webpack);
var path= require(path);
var DIST_DIR=path.resolve(__dirname,"dist");
var SRC_DIR= path.resolve(__dirname,"src");
var config={
entry:SRC_DIR+"/app/index.js",
output:{
path:DIST_DIR+"/app",
fileName:bundle.js,
publicPath:"/app/",
},
devServer: {
inline: true,
port: 7777
},
modules:{
loaders:[
{
test:/\.js?/,
include:SRC_DIR,
loader:"babel-loader",
query:{
presets:["react","es2015","stage-2"]
}
}
]
}
};
module.exports=config;
So now whenever I run the command npm start,it gives the following error:-
Being a beginner I have no idea as what is the issue?? If anyone has come across this similar issue or knows about the error,please contribute your knowledge and show me the right path.

change
output:{
path:DIST_DIR+"/app",
fileName:bundle.js,
publicPath:"/app/",
},
to
output:{
path:DIST_DIR+"/app",
fileName:"bundle.js",
publicPath:"/app/",
},

It seems that you forgot the quotes when you were requiring the npm modules:
var webpack= require('webpack');
var path= require('path');

Related

How to add React component to a website using babel

I'm trying to add a React component to a website using babel. Here's official React documentation tutorial but I could not make it work.
Here's my index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="theme-color" content="#000000"/>
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="https://unpkg.com/react#18/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#18/umd/react-dom.production.min.js" crossorigin></script>
<script src="build/index.js" type="text/babel"></script>
</body>
</html>
Here's my src/index.js
import React from 'react'
import ReactDOM from 'react-dom/client'
function App() {
return (
<button>Like me!</button>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Here's my package.json
{
"name": "react-project",
"version": "1.0.0",
"description": "",
"main": "src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"#babel/cli": "^7.20.7",
"#babel/core": "^7.20.12",
"#babel/preset-react": "^7.18.6"
}
}
Then I run in terminal:
./node_modules/.bin/babel src --out-dir build --presets #babel/preset-react
It creates build/index.js which is added to my index.html:
import React from 'react';
import ReactDOM from 'react-dom/client';
function App() {
return /*#__PURE__*/React.createElement("button", null, "Like me!");
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( /*#__PURE__*/React.createElement(App, null));
When I open index.html in browser - nothing happens, button does not appear.
This whole story works only if I add <script src="https://unpkg.com/#babel/standalone/babel.min.js"></script> to my index.html but this is not what I want.
What do I do wrong?
because babel only compiles jsx the esm syntax remains and you have nothing to deal with them (a compiler or esm itself with type='module' and cdn esm or importmap)
for starters use powerful tools like vite

Vue3 - imported module is undefined

Update: After downgrading vue-cli to 4.5.19 code is working fine.. So I think it's issue related with vue-cli or its dependency.
I've created simple vue.js project using vue-cli. After adding to the project package timecode by npm install timecode --save and try to use it in Vue component, imported module is undefined. I've a feeling this is problem related with webpack. Timecode package is written in commonJS and when I use it outside this project, it works fine. Any ideas?
#vue/cli v5.0.8,
npm v8.11.0,
node v16.16.0
package.json
{
"name": "hello-world",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build"
},
"dependencies": {
"core-js": "^3.8.3",
"timecode": "^0.0.4",
"vue": "^3.2.13"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~5.0.0",
"#vue/cli-service": "~5.0.0"
}
}
vue.config.js
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true
})
babel.config.js
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset'
]
}
main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
App.vue
<template>
<HelloWorld />
</template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
export default {
name: "App",
components: {
HelloWorld,
},
};
</script>
<style>
</style>
HelloWorld.vue
<template></template>
<script setup>
import timecode from "timecode";
console.log(timecode); // { }
const timeCode = timecode.Timecode; // undefinied
const tc = timeCode.init({ framerate: "29.97", timecode: "01:00:00:00" }); // Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'init')
tc.add(4);
tc.add("00:02:03:00");
console.log(tc.toString());
</script>
<style>
</style>
Output in console
app.js:167 Uncaught TypeError: Cannot read properties of undefined (reading 'init')
at setup (HelloWorld.vue?e90b:7:1)
at callWithErrorHandling (runtime-core.esm-bundler.js?d2dd:155:1)
at setupStatefulComponent (runtime-core.esm-bundler.js?d2dd:7186:1)
at setupComponent (runtime-core.esm-bundler.js?d2dd:7140:1)
at mountComponent (runtime-core.esm-bundler.js?d2dd:5493:1)
at processComponent (runtime-core.esm-bundler.js?d2dd:5468:1)
at patch (runtime-core.esm-bundler.js?d2dd:5058:1)
at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js?d2dd:5607:1)
at ReactiveEffect.run (reactivity.esm-bundler.js?89dc:185:1)
at instance.update (runtime-core.esm-bundler.js?d2dd:5714:1)
When I use this package, without vue, by simple npm init, npm install timecode --save and call it form node node index.js I don't have this problems.
index.js
const timecode = require("timecode").Timecode; // all fine
const tc = timecode.init({ framerate: "29.97", timecode: "01:00:00:00" });
tc.add(4)
tc.add("00:02:03:00");
tc.toString();
package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"timecode": "^0.0.4"
}
}
If you are using Vue 3 Composite API you can register the package locally and use it
<template>
</template>
<script setup>
import timecode from 'timecode'
//create the constant value and assign it with the imported timecode
const timeCode = timecode.Timecode;
const tc = timeCode.init({ framerate: "29.97", timecode: "01:00:00:00" });
tc.add(4);
tc.add("00:02:03:00");
console.log(tc.toString());
</script>
<style>
</style>
If you are using Vue 3 Optional API you can try like this.
<template>
</template>
<script>
import timecode from 'timecode'
export default {
data: () => ({
timeCode: timecode.Timecode
}),
methods: {
//create a function to use your time code
useMyTimeCode() {
let tc = this.timeCode.init({ framerate: "29.97", timecode: "01:00:00:00" });
tc.add(4);
tc.add("00:02:03:00");
console.log(tc.toString());
}
},
created() {
//you can use you function anywhere and you can even modify the function to pass parameters
this.useMyTimeCode();
}
}
</script>
<style>
</style>
Remember to install the package as
npm i timecode

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.

Embedded react component not rendered/loaded in html page. (webpack/babel)

I am trying to set up my first Webpack Babel React project.
Although the html code shows on various browsers (http://localhost:80), the embedded react component is not loaded. The following message can be read in the console
"Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
at invariant (transformed.js:304)"
Click here to see error image
Find below the different config and code files setting up this environment.
./app/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My first local App</title>
</head>
<body>
<div id='app'> </div>
<h1> Testing </h1>
</body>
</html>
./app/index.js
var React = require('react');
var ReactDOM = require('react-dom');
var App = require('../components/App');
ReactDOM.render(
<App />,
document.getElementById('app')
);
./components/App.js
import React from 'react';
import ReactDOM from 'react-dom';
export class App extends React.Component {
constructor(){
super();
console.log('Component has been constructed ')
}
render() {
return (
<div>
<h1>This is a simple test</h1>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
package.json
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"deploy":"npm run build && npm run git-commit && npm run git-push",
"build": "webpack",
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^15.6.1",
"react-dom": "^15.6.1"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^2.30.1",
"webpack": "^3.4.1",
"webpack-dev-server": "^2.6.1"
}
}
.babelrc
{presets:["react"]}
webpack.config
var HTMLWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HTMLWebpackPlugin ({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: __dirname + '/app/index.js' ,
module: {loaders: [ {test:/\.js$/, exclude:/node_modules/, loader:'babel-loader' } ]},
output: {filename: 'transformed.js', path: __dirname + '/build'},
plugins: [HTMLWebpackPluginConfig],
resolve : { extensions: [".js", ".jsx"] }
};
Thanks,
Sebastian
Looks like you have
ReactDOM.render(
<App />,
document.getElementById('app')
);
in there twice. Could be other errors as well, but remove it from App.js and see if that helps.
At first, remove second render in <App />, at second, change var App = require('../components/App'); to import {App} from '../components/App'; And your error must gone.

Facing some issues with ReactJS first program

I just started learning ReactJS, I am following this tutorials here.
egghead.io I just completed its first video and developed an app as shown in video, But some how I can see the html part but failed to load the dynamic content coming from the App.js Below is my code:
App.js
import React from 'react';
class App extends React.Component {
// always expected to return
render() {
return '<div><h4>Hello World of ReactJS</h4></div>'
}
}
export default App;
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ReactJS Tutorial</title>
</head>
<body>
<h1>ReactJS First Project</h1>
<div id="app">
</div>
<script src="index.js"></script>
</body>
</html>
main.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render('<App/>' , document.getElementById('app'));
package.json
{
"name": "App",
"version": "1.0.0",
"description": "First application of ReactJS",
"private": true,
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "AD",
"license": "Apache",
"dependencies": {
"babel-core": "^6.13.1",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.13.1",
"babel-preset-react": "^6.11.1",
"react": "^15.3.0",
"react-dom": "^15.3.0"
},
"devDependencies": {
"webpack-dev-server": "^1.9.0"
}
}
webpack.config.js:
module.exports = {
entry: "./main.js",
output: {
path: "./",
fileName: "index.js"
},
devServer: {
inline: true,
port: 3333
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
Would need some help to run it, not sure. I have installed everything as asked in the video, I am using node 6.2.2.
In your main.js, change:
ReactDOM.render('<App/>' , document.getElementById('app'));
to
ReactDOM.render(<App/>, document.getElementById('app'));
The quotes are the problem. You want to render your imported component, not some String. Also I would be interested if you got a warning in the console.

Categories

Resources