On the fly LESS compiler for java web app?

拥有回忆 提交于 2019-12-31 12:57:43

问题


I am looking for a way to compile CSS LESS files on the server side on demand during development. For example if the browser makes a request to /assets/css/foo.css I want the server to notice that there is an /assets/css/foo.less file and then to have this file complied and the resulting css returned. I am guessing there must be a LESS servlet somewhere that can do this?

I am running tomcat 7 with Spring MVC application

How do I configure a Java Web App to do on the fly LESS compilation?


回答1:


I think what you are looking for is a Servlet Filter. I was not aware of an off the shelf one that does LESS compiling and would have started to make one using lesscss-java, but now I can see there is a larger project called Web Resource Optimizer for Java - wro4j with server side LESS support.




回答2:


It would be simpler (and more effective) to first compile your less files to css files, during the build of your webapp.
As an example, when using Maven, we use the lesscss-maven-plugin (compile goal, process-sources phase) to generate css files from less files. Then only the css files are used and packaged in the webapp. No less files are used dynamically.
Another advantage is that less files are compiled before the webapp is deployed, so compilation errors are detected sooner.

Configuration example in pom.xml :

<plugin>
    <groupId>org.lesscss</groupId>
    <artifactId>lesscss-maven-plugin</artifactId>
    <version>1.3.0</version>
    <configuration>
        <sourceDirectory>${project.basedir}/src/main/webapp/less</sourceDirectory>
        <outputDirectory>${project.build.directory}/${project.build.finalName}/css</outputDirectory>
        <compress>true</compress>
        <includes>
            <include>main.less</include>
        </includes>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>compile</goal>
            </goals>
        </execution>
    </executions>
</plugin>



回答3:


What we do is we have two modes : dev and production.

For dev, use the official less css js compiler, which compiles on the fly:

<link type="text/css" rel="stylesheet/less" href="${...}/style.less" />
<script>(window.less = window.less || {}).env = 'development';</script>
<script src="${staticContext}/lib/less-1.3.3.js"></script>

in your HTML

for prod, use the compiled styles by https://github.com/marceloverdijk/lesscss-maven-plugin

<link type="text/css" rel="stylesheet" href="${staticContext}/css/style.css" />


来源:https://stackoverflow.com/questions/13868734/on-the-fly-less-compiler-for-java-web-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!