文章

Configure grunt for livereload with tomcat

In JEE project, tomcat or jetty is always used for local development. We build the WAR file and deploy to tomcat. Once the WAR is expanded on the server folder, front end changes to files like js/css/jsp can be directly copied to to the server for faster development. An ant script like this would help such process:

<target name="copy-web-files">
    <copy todir="${tomcat.home}/webapps/${app.name}" preservelastmodified="true">
        <fileset dir="${app.dir}/src/main/webapp">
            <include name="**/*.js"/>
            <include name="**/*.css"/>
            <include name="**/*.jsp"/>
        </fileset>
    </copy>
</target>

Execute the task and refresh browser and you’re done. You can do better than this by grunt.js.

grunt.initConfig({
    watch:{
        server:{
            files:[
                "src/main/webapp/**/*.js",
                "src/main/webapp/**/*.css",
                "src/main/webapp/**/*.jsp"
            ],
            task: ['copyto'],
            options: {livereload: true}
        }
    },
    copyto:{
        stuff:{
            files:[
                cwd: 'src/main/webapp/',
                src: ["**/*.js", "*/*.css", "**.*.jsp"],
                dest: "<%=prop.tomcat_home%>\\webapps\\<%=prop.app_name%>"
            ]
        }
    }
});

In this grunt config, the tasks grunt-contrib-watch and grunt-copy-to are used. Run grunt watch will watch for file changes, copy modified files and trigger livereload.

*