Looking to optimize the performance of your Spring Boot Application? (Who isn’t?) Sure, you could pull JavaScript and CSS files from a CDN, but for a real performance upgrade you probably want to try bundling your assets with webpack! In a previous tutorial you created a web application using React and Bootstrap that pulled libraries into HTML manually. In this post, you’ll learn how to use webpack to organize your imports more effectively.
Start a New React Application with Spring Boot
Start by cloning the previous application and making sure you have Stormpath configured with a ~/.stormpath/apiKey.properties
file. It should then boot with Maven.
mvn spring-boot:run
Open your browser and navigate to http://localhost:8080. This presents you with a login screen, and once you’re logged in a styled data table.
Convert HTML
Now, strip out the external JavaScript and CSS imports in src/main/resources/templates/index.html
. Also remove the Babel specifier in your local script and change app.js
to bundle.js
.
React + Spring
Move your app.js
from src/main/webapp/public
to src
.
Webpack Configuration
Configure webpack by creating a file called webpack.config.js
in the root directory. It defines a Node-style export module.
module.exports = { entry: './src/app.js', output: { path: __dirname + '/src/main/webapp/public', filename: 'bundle.js' } };
entry
is the starting point of your app or component. It is the main method of your code and is where webpack builds a dependency graph from.
output
is where the bundled assets should end up. You put it into src/main/webapp/public
because that is where Spring Boot serves out static files to the public.
Run Webpack from the Command Line
With the configuration file complete, all you need to do is run webpack
from the command line.
Note: if you haven’t done so already install webpack globally with npm install -g webpack
.
You’ll see an error that mentions ‘Unexpected token’. This is because your script is written in ES6 and you need to convert it to common Javascript. You do this with loaders in your webpack.config.js
.
Use Loaders
Loaders process assets before being bundled. You include them in your webpack.config.js
.
module.exports = { entry: './src/app.js', output: { path: __dirname + '/src/main/webapp/public', filename: 'bundle.js' }, module: { loaders: [ { test: /.js$/, loader: 'babel', exclude: /node_modules/, query: { presets: ['es2015', 'react'] } } ] } };
You’ve specified that any file ending in .js
should be processed with the Babel loader, except for those in the node_modules
directory, using the es2015 and React Babel presets.
You also need to install these modules using npm
. However, you’ll need a package.json
file first. To create one, run npm init
. The values I used below are defaults or examples.
$ npm init This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. See `npm help json` for definitive documentation on these fields and exactly what they do. Use `npm install--save` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. name: (stormpath-spring-boot-react-example) version: (1.0.0) description: Spring Boot + React + Webpack entry point: (webpack.config.js) test command: git repository: (https://github.com/stormpath/stormpath-spring-boot-react-example.git) keywords: author: license: (ISC) About to write to /Users/mraible/dev/stormpath-spring-boot-react-example/package.json: { "name": "stormpath-spring-boot-react-example", "version": "1.0.0", "description": "Spring Boot + React + Webpack", "main": "webpack.config.js", "dependencies": { "babel-loader": "^6.2.7", "babel-preset-es2015": "^6.18.0", "babel-preset-react": "^6.16.0" }, "devDependencies": {}, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/stormpath/stormpath-spring-boot-react-example.git" }, "author": "", "license": "ISC", "bugs": { "url": "https://github.com/stormpath/stormpath-spring-boot-react-example/issues" }, "homepage": "https://github.com/stormpath/stormpath-spring-boot-react-example#readme" } Is this ok? (yes) yes
After creating package.json
, you should be able to install the necessary dependencies.
npm install --save-dev babel-loader babel-preset-es2015 babel-preset-react
You might see some warnings about peer dependencies not being met. If you do, run the following command:
npm install --save-dev babel-core webpack
Now when you run webpack
from the command line, you should see a success message!
Add Dependencies
If you refresh the page, you’ll see only the login button appears, unstyled. Loading the console shows that React was not found in bundle.js
.
You need to import the libraries to app.js
.
import React from 'react'; import ReactDOM from 'react-dom'; import $ from 'jquery'; import toastr from 'toastr';
Also, pull the libraries in locally using npm
.
npm install --save react react-dom jquery toastr
After running webpack
again and refreshing your browser, you should see your component but without styling.
Style Your CSS
To get styling to work you once again need to install the required libraries using npm
.
npm install --save bootstrap
Now import the style files directly into your app.js
.
import 'bootstrap/dist/css/bootstrap.css'; import 'toastr/build/toastr.css';
Finally, add loaders for both the CSS files and for any assets the CSS might reference.
{ test: /\.css$/, loader: 'style!css' }, { test: /\.(woff2?|ttf|eot|svg|png|jpe?g|gif)$/, loader: 'file' }
style!css
means first use style-loader
and then pass it to css-loader
. Install the loaders via npm
.
npm install --save-dev style-loader css-loader file-loader
Now when you run webpack
, you should see successful output and the various assets that were converted.
Refresh your page, and you should see the same, fully styled component as before.
You’ve just converted your React/Bootstrap app over to webpack!
Command Line Options for Webpack
There are many things you can do with webpack. For example, to minify your bundles for production just add -p
when you build.
webpack -p
You can also use -w
to watch for changes and build automatically.
Splitting Out CSS
You might also want to split your CSS out into a separate bundle. This can be achieved with the ExtractTextPlugin. First, install the plugin via npm
.
npm install --save-dev extract-text-webpack-plugin
Now change your CSS loader to use the plugin. Start by importing the plugin at the top of your webpack.config.js
.
var ExtractTextPlugin = require('extract-text-webpack-plugin');
Then replace the CSS loader.
{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }
Finally, add a plugins section below module.
module: { ... }, plugins: [ new ExtractTextPlugin("styles.css") ]
Now you can update your HTML to pull in the new bundle.
Integrate with Gulp
If you need to automate external tasks you can integrate your webpack setup with Gulp. Start by installing Gulp and the webpack stream utility.
npm install --save-dev gulp webpack-stream
Then create the following gulpfile.js
.
var gulp = require('gulp'); var webpack = require('webpack-stream'); gulp.task('default', function() { return gulp.src('src/entry.js') .pipe(webpack(require('./webpack.config.js'))) .pipe(gulp.dest('src/main/webapp/public')); });
Now running gulp
from the command line will run your webpack configuration as before.
Components Everywhere!
The prevailing ethos on designing the web is component-based. Applications are split into reusable pieces. React is a leader in this regard.
Writing traditional HTML to support components doesn’t make sense. Manually pulling in assets, libraries such as jQuery or stylings like Bootstrap, quickly becomes a mess. Webpack solves this for you!
I hope this tutorial has shown you how easy it is to configure webpack in your React application. To view the finished code, check out the GitHub repo.
Or, if you’re interested in learning more about React or Spring Boot, check out one of these great resources:
- Tutorial: Let’s Build a Redux-Powered React Application
- Tutorial: Build a React Application with User Authentication
- Tutorial: Get Started with Angular, Spring Boot, and Stormpath
The post Optimize Your React Application with Webpack in 15 Minutes appeared first on Stormpath User Identity API.