how to integrate ReactJs with Spring MVC in eclipse - eclipse

I am a new to ReactJS, before I used angularJS for my client side. But now I want to integrate it with the present application on SpringMVC. Now I want to integrate ReactJS as client side instead of angularJS, please help me. If there is any example please help. I am using eclipse ide.

Try to create a view(jsp/html/xhtml) and link the UI build output to that. you may use webpack as a build tool for UI(React) which will return bundle file.
Then it can be included to view using script tag. Please note you can use webpack-dev-server for UI development and try to use Proxy to consume the spring-mvc service. Its a recommended way. A folder containing all the JS under webapp can be used if your using Maven as build tool for java.
webpack reference : https://webpack.js.org/
Sample Webpack.config.js for reference.
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
main: './src/scripts/main.js',
engine: './src/scripts/engine/Engine.js',
debugger: './src/scripts/debug/Debugmain.js',
client: './src/scripts/clientcode/Client.js'
},
output: {
path: path.resolve('./dist/client'),
filename: '[name].js',
publicPath: '/dist/client/',
chunkFilename: '[name].js'
},
devtool: 'inline-sourcemap',
cache: true,
resolve: {
alias: { ByteBuffer: 'bytebuffer' }
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'react-hot-loader'
},
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
cacheDirectory: true,
presets: ['react', 'es2015'],
compact: false
}
},
{
enforce: 'pre',
test: /\.(js|jsx)$/,
exclude: /node_modules/,
include: [path.join(__dirname, './src', 'scripts')],
loader: 'eslint-loader'
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
loader: 'css-loader?sourceMap!less-loader?sourceMap'
})
},
{
test: /\.(eot|woff|woff2|ttf|otf|png|jpg)$/,
loader: 'file-loader?name=images/[name].[ext]'
}
]
},
devServer: {
port: 8080,
stats: 'errors-only',
proxy: {
'/api': {
target: 'http://localhost:20404', //http://localhost:20403/',
secure: false
}
},
historyApiFallback: {
index: 'debug.html'
}
},
plugins: [
new ExtractTextPlugin({
filename: './styles/main.css',
allChunks: true
})
],
resolve: {
modules: ['src/scripts', 'node_modules'],
extensions: ['.jsx', '.js'],
unsafeCache: true,
alias: {
components: path.resolve(__dirname, 'src', 'scripts', 'components'),
routes: path.resolve(__dirname, '.', 'routes'),
draggable_tab: path.resolve(__dirname, 'src', 'scripts', 'lib'),
utils: path.resolve(__dirname, 'src', 'scripts', 'utils'),
engine: path.resolve(__dirname, 'src', 'scripts', 'engine')
}
}
};

Related

What should the publicPath in webpack config be for a dynamic port?

I'm currently building a microfrontend using webpack's module federation, however when I create a deployment in kubernetes it's not resolving because of an incorrect publicPath. It's still a bit complex to me and I'm not sure what to set the publicPath to as the localhost port keeps changing every deployment.
So it looks like: http://127.0.0.1:TUNNEL_PORT, whereby TUNNEL_PORT is dynamic. How would I account for this when defining my output.publicPath?
Webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
const deps = require("./package.json").dependencies;
module.exports = {
output: {
publicPath: "http://localhost:3000/",
// publicPath: 'auto',
},
resolve: {
extensions: [".tsx", ".ts", ".jsx", ".js", ".json"],
},
devServer: {
port: 3000,
historyApiFallback: true,
},
module: {
rules: [
{
test: /\.m?js/,
type: "javascript/auto",
resolve: {
fullySpecified: false,
},
},
{
test: /\.(css|s[ac]ss)$/i,
use: ["style-loader", "css-loader", "postcss-loader"],
},
{
test: /\.(ts|tsx|js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
],
},
plugins: [
new ModuleFederationPlugin({
name: "microfrontend1",
filename: "remoteEntry.js",
remotes: {},
exposes: {
"./Header": "./src/Header.tsx",
"./Footer": "./src/Footer.tsx",
},
shared: {
...deps,
react: {
singleton: true,
eager: true,
requiredVersion: deps.react,
},
"react-dom": {
singleton: true,
eager: true,
requiredVersion: deps["react-dom"],
},
},
}),
new HtmlWebPackPlugin({
template: "./src/index.html",
}),
],
};

Babelrc configuration for IE11 support

I am trying to configure .babelrc for my react project but, cant make it work in IE11.
Can someone take a look at my configuration and see if there are things that I am missing, please?
[.babelrc]
{
"presets": [
"#babel/preset-env",
[
"#babel/preset-react",
{
"useBuiltIns": "usage",
"corejs": 3.26
}
]
],
"plugins": ["#babel/plugin-transform-runtime"]
}
[webpack.common.config.js]
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require("path");
module.exports = {
// Default. Can be erased for code simplification
entry: "./src/index.js",
output: {
filename: "[name].[contenthash].js",
path: path.resolve(__dirname, "dist"),
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /[\\/]node_modules[\\/]/,
use: {
loader: "babel-loader",
},
},
{
test: /\.scss$/,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "src", "index.html"),
}),
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css",
}),
],
};
I have tried a lot of things(workarounds), but nothing seems to work.
The order of presets, importing core-js at the top of index.js file...

How to get grunt serve task working alongside watch?

I've recently installed and got a it up and running but I can't seem to get it running concurrently with my watch task? In my grunt file, if register the serve task before watch, the server spins up and but the watch task doesn't....and vice versa. This is the serve package and Im using and Grunt file attached:
https://www.npmjs.com/package/grunt-serve
module.exports = function(grunt) {
// 1. All configuration goes here
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
dist: {
src: [
'js/libs/*.js', // All JS in the libs folder
'js/global.js' // This specific file
],
dest: 'js/build/production.js',
}
},
uglify: {
options: {
mangle: false
},
my_target: {
files: {
'js/build/production.min.js': ['js/build/production.js']
}
}
},
imagemin: {
dynamic: {
files: [{
expand: true,
cwd: 'images/',
src: ['**/*.{png,jpg,gif}'],
dest: 'images/build/'
}]
}
},
sass: {
//options: {
// style: 'compressed'
//},
dist: {
files: [{
expand: true,
cwd: 'css',
src: ['*.scss'],
dest: 'css/build/',
ext: '.css'
}]
}
},
serve: {
options: {
port: 9000
}
},
watch: {
options: {
livereload: true,
},
css: {
files: ['css/**/*.scss'],
tasks: ['sass'],
options: {
spawn: false,
}
},
scripts: {
files: ['js/*.js'],
tasks: ['concat', 'uglify'],
options: {
spawn: false,
},
}
}
});
// Load all Grunt tasks automatically wihtout having to enter manaually
require('load-grunt-tasks')(grunt);
grunt.registerTask(
'default',
[
'concat',
'uglify',
'sass',
'serve',
'watch'
]
);
};
Grunt serve and grunt watch are both blocking tasks. You can use a plugin like grunt-concurrent to run both at the same time in separate threads. https://github.com/sindresorhus/grunt-concurrent
concurrent: {
target1: ['serve', 'watch'],
}
//aslo update your default task
grunt.registerTask(
'default',
[
'concat',
'uglify',
'sass',
'concurrent:target1'
]
);
Additionally you could also use grunt-concurrent to run your uglify and sass tasks in parallel which may improve build time.

Can't set breakpoint in Chrome with Babel and Webpack

I have started a new project using the "new" stack: React+Webpack+Babel.
I am trying to explore of this work, and I am facing an issue with debugging in chrome. I can't set breakpoints on some lines in source files when I use Babel and Webpack. (I create sourcemaps).
I would like to be able to debug JSX files.
I have set a little project to reproduce the problem.
https://github.com/pierre-hilt/babel_webpack_sourcemap.git
Here is my configuration:
var path = require('path')
var webpack = require('webpack')
module.exports = {
devtool: 'source-map',
entry: './build/index',
output: {
path: path.join(__dirname, 'static'),
filename: '[name].bundle.js',
publicPath: '/',
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
loader: "source-map-loader"
}
]
},
resolve: {
extensions: ['', '.js', '.jsx'],
},
}
babelrc:
{
"presets": [
"es2015",
"react"
],
"plugins": []
}
App.jsx (I try to break on line 6 but it is impossible...)
import React, { Component, PropTypes } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
title: props.title,
};
}
changeTitle(newTitle) {
this.setState({ title: newTitle });
}
render() {
return (
<div>
This is {this.state.title}
</div>
);
}
}
App.propTypes = { title: PropTypes.string };
export default App;
I tried different devtool options (cheap, module, ...).
I also tried Babel loader, but is does not work either.
Do you have any idea? Is it a known issue?
OK, I found a workaround that works fine!
babelrc
{
"presets": [
"react"
],
"plugins": []
}
Babel script
"babel": "babel client -d build --source-maps",
webpack config
var path = require('path')
var webpack = require('webpack')
module.exports = {
devtool: 'source-map',
entry: './build/index',
output: {
path: path.join(__dirname, 'static'),
filename: '[name].bundle.js',
publicPath: '/',
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
loader: "source-map-loader"
}
],
loaders: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel', // 'babel-loader' is also a legal name to reference
query: {
presets: ['es2015']
}
}
]
},
resolve: {
extensions: ['', '.js', '.jsx'],
},
}
I first transpile JSX with babel only, then I transpile ES2015 with babel loader and webpack.
At the end I got source files where I can set break points anywhere!

Webpack Karma cannot resolve local import

I am using Webpack for both the app and tests (using https://github.com/webpack/karma-webpack for it). The app is in typescript and the tests in Babel.
Importing something from a standalone module in the tests works (using import { cleanHTML, fromHTML, toHTML } from "../../app/utils/text.ts";, ie I need to mention the .ts extension otherwise it fails).
When I actually try to import a React component that imports a component in another file, I get the following error:
Module not found: Error: Cannot resolve 'file' or 'directory' ./blocks/paragraph.
The tree of directory looks like:
src/
app/
components/
blocks/
paragraph.ts
main.ts
tests/
components/
main_tests.js
utils/
And the main.ts imports paragraph.ts like so import { ParagraphBlockComponent } from "./blocks/paragraph";
Normal compilation works but not the tests.
Here is the karma config:
var path = require('path');
module.exports = function (config) {
config.set({
basePath: 'src',
singleRun: true,
frameworks: ['mocha', 'chai'],
reporters: ['dots'],
browsers: ['Firefox'],
files: [
'tests/index.js'
],
preprocessors: {
'tests/index.js': ['webpack']
},
webpack: {
noInfo: true,
module: {
loaders: [
{
test: /\.ts$/,
loaders: ['awesome-typescript-loader']
},
{
test: /\_tests.js$/,
loaders: ['babel-loader']
}
]
}
},
webpackMiddleware: {
noInfo: true,
stats: {
color: true,
chunkModules: false,
modules: false
}
}
});
};
Did I miss something?
Adding the following to the karma webpack config fixed it for me
resolve: {
extensions: ['', '.js', '.ts']
},