gjvatsalya gjvatsalya - 1 year ago 130
React JSX Question

Is it possible to integrate React (using Webpack) with Grails?

I've been thinking about using React as the frontend for a Grails application, but I'm having a bit of trouble getting started.

So far, I've become accustomed to write a React app using Node/NPM with the help of Webpack, and that's been pretty easy because there is plenty of documentation for that setup.

However, I'm struggling to find anything concrete integrating React seamlessly with Grails.

Ideally, I would just do

grails run-app
and it should take care of everything. I do not want other team members to worry about starting up two different servers or something along those lines.

Please let me know if anyone has done this before.

Answer Source

Webpack can be configured to work quite well with Grails. The key is to have webpack generate its bundle whenever the app is started up, and to output the bundle in a directory where it can be served from the GSP. You do not want your source JavaScript (I.e, React/ES6 code) in the asset pipeline if your using Webpack, instead you want to keep those source files in another directory (such as src/webapp), and configure Webpack to bundle these files and output the result to the asset pipeline (assuming you're using AP at all).

Here's an example configuration for Webpack:

var path = require('path');

module.exports = {
    entry: {
        index: './src/webapp/index.js'
    output: {
        path: './grails-app/assets/javascripts',
        publicPath: '/assets/',
        filename: 'bundle.js'

Finally, to achieve the integrated webpack/Grails startup, you can use the Gradle node plugin and attach the webpack run script to the application startup in a custom task in your build.gradle (this is assuming that you have a npm script named "webpack" defined to run webpack)

assetCompile.dependsOn(['npmInstall', 'npm_run_webpack'])

Please note that if you want to run webpack in "watch" mode, you'll need to do that seperately from starting up the Grails app, so that that script can run continuously (there actually is support for this in the Gradle mode plugin but it's currently broken).

See this link for a more in-depth explanation of this approach, with a sample application: http://grailsblog.objectcomputing.com/posts/2016/05/28/using-react-with-grails.html

Also checkout the React profile for Grails 3: https://github.com/grails-profiles/react

It has not been released yet but should be in the next few days. It makes use of the same approach outlined here and in the linked post.