• home > tools > Bundler > grunt >

    php和jsp项目的前端工程一体化!

    Author:[email protected] Date:

    比如,jsp,php,项目,css,js,————以及前端工程怎么样构建?php,或者jsp,但是grunt-live watchphp或者jsp,php和jsp项目的前端工程一体化!工程架构什么怎么样的?

    做前端前我是一名php狗,然后再自己搞半调子java,什么eclipse,net bean,最后选择了intellij……

    现在eclipse的快捷键最基本忘记了……

    intellij也可以,在chrome上面装插件,然后就 自动化了?……神器哈!

    但是,无碍grunt……有glup后,还是钟爱………

    管理台这一块,都是,angularjs,然后livereload搞定……

    但是,php or jsp 呢?

    难道要手工……——懒惰的程序猿才是好的程序员!+深深地认可的天理!!!

    百度下,木有任何答案……每次都要诅咒 GC ***邪恶的组织一万遍……

    20160411104302242.png


    然后早就只有动手了……

    然后grunt 搜到了个 grunt-php -oh,牙买跌!!

    传送:https://www.npmjs.com/package/grunt-php


    推荐配置:


    module.exports = function(grunt) {    
    grunt.initConfig({    
    pkg: grunt.file.readJSON('package.json'),    
    php: {    
    dev: {    
    options: {    
    hostname: '127.0.0.1',    
    port: 5000    
    }    
    }    
    },    
    less: {    
    dev: {    
    files: {    
    "style.css": "style.less"    
    }    
    }    
    },    
    watch: {    
    markup: {    
    files: ['index.php'],    
    options: {    
    livereload: true,    
    }    
    },    
    styles: {    
    files: ['style.less'],    
    tasks: ['less:dev'],    
    options: {    
    livereload: true    
    }    
    },    
    }    
    });    
    // Tasks.    
    grunt.loadNpmTasks('grunt-php');    
    grunt.loadNpmTasks('grunt-contrib-watch');    
    grunt.loadNpmTasks('grunt-contrib-less');    
    grunt.registerTask('default', ['php:dev', 'watch']);    
    };
    <!DOCTYPE html>    
    <html>    
    <head>    
    <title></title>    
    <link rel="stylesheet" type="text/css" href="style.css">    
    </head>    
    <body>    
    <?php echo "Hello"; ?>    
        <script src="http://localhost:35729/livereload.js"></script>    
    </body>    
    </html>

    其实这位大哥解决的更详细:

    Running an on-demand PHP server with BrowserSync and Grunt/Gulp

    http://fettblog.eu/php-browsersync-grunt-gulp/

    我只好闭嘴了……

    如歌是jsp,暂时没有解决好的方案……

    只好 尼玛,干脆,直接把编辑的文件,copy到tomcat目录下……

    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%>"
                ]
            }
        }
    });


    老外用maven搞定!不翻译了……

    The first question is why do you have to mix them both ? - What is the need to use Node & NPM in a Java based web app ?

    There are some advantages on the presentation engineering front, in having Node as part of your maven build process for a Java based Web Application, or having it in any web app for that matter. Here, this post specifically talks about integrating Node & NPM with Java & Maven based projects. In short,

    Better manage your presentation engineering front by integrating Node & NPM

    Some of the advantages of having Node & NPM as part of Maven Builds for the presentation engineering front of your product is:
    1. You can firstly download a Node executable & run it.
         You can use this & run various JS automation tasks via Grunt.
    2. Install the Node Package Manager & use it. This helps to author your JS in 
        a modular fashion in the Common JS Style, with NPM managing dependencies.
    3. Write grunt tasks & use Grunt as an automation JS task runner
    4. Lint the JS & CSS files using grunt-contrib-jsHint and grunt-contrib-cssLint
    5. Check for circular dependencies in your Javascript code using the NPM Madge       plugin. Cyclic dependencies are a sign that you may want to re-org your code in     a better manner. The NPM Madge plugin force breaks the maven build, as the         grunt task would fail, if it detects cyclic dependencies. This enforces developers     to use better patterns while coding.
    6. Helps you to modularize the code. Modularization in JS now follows the 2               major syntaxes - common JS (or) AMD patterns
    7. How can integration of Node / NPM help you with modularization ? - Well you 
        either need to use Browserify to convert your common JS modules into browser
        compatible modules (or) you may want to write a Grunt Task to create a build to
        run the r.js optimizer to build all the AMD modules. There are Grunt tasks for it.
        And you need Node & NPM for the same.
    8. You could quit using Grunt and use the streaming build system of Gulp.
    9. Templates can be pre-compiled which leads to quicker rendering.
         Underscore Templates are pre-compiled with the Grunt Task called 
         grunt-contrib-jst (for eg.)
    10. Besides all this, there are plugins in grunt that help to compress images,
          convert images into sprites, Base64 encode images which leads to 
          further optimizations while rendering. 
    11. You could write a grunt task to execute a Bower Job to manage front end
          dependencies. As much as NPM is a package manager by itself, it has
          issues with multiple copies for the same resource as it operates on a nested
          structure. Bower however maintains only one copy for every resource as it 
          has a flat structure. This is why Bower distinguishes itself as the Front End
          package manager for the web.
    12. Unit Testing code : How much attention are we paying to Unit Testing                     Javascript code ? - Grunt can also be used to run a karma task. Karma is a test
          runner / executor. This could be used with Mocha & chai (Assertions) to unit           test code, run the test cases on a headless Phantom JS & generate                         coverage reports on Istanbul. These can be included as part of the maven
          build process. 
    13. Also, one more reason to use this is Grunt itself! - You can minify, compress
          CSS & obfuscate / uglify JS, concatenate, copy files to improve rendering               speed, via Grunt.
    14. Further, Use the docco-plus plugin to properly author JS docs. Also, you can
          use Grunt LESS / SASS plugins to process them.
    15. Grunt can also be used to watch file for changes & live reload them to your 
          browser.

    Making Maven Grunt:
    The power of Node to run Grunt Tasks with NPM, Bower managing dependencies, is one of the major reasons for using Node & NPM as part of the Maven build process for a Java based web project. Bower manages front end dependencies such as libraries of jQuery / Angular / Underscore etc.,

    This setup helps to better manage & improve the presentation performance, maintainability of the pages & your site as a whole, by adhering to standards. 

    The presentation framework can continue to remain whatever it was before - JSP, JSF, Velocity, Templates etc., Your original server continues to be whatever it was before!

    The Maven plugin pre-requisites:
    Out of the various plugins available Like the YeoMan Maven plugin, Ant Run Maven plugin, Node Maven Plugin etc., the Front End Maven Plugin is the one that truly encompasses all our required functionality, that you may want to do with Node, for a Java - Maven application.

    The Front End Maven plugin downloads & runs a Node executable, installs NPM, runs Grunt / Gulp & Bower & even karma Tasks. The Front End maven plugin is also platform agnostic and works on Linux Win OS X. The plugin outshone all the others, in the evaluations and comparisons we did. 

    In the following example, we look at a bare bones implementation of the same
    by installing Node, NPM, running Grunt to execute the R.js optimizer to build the
    AMD require Module, uglify it and generate a build output file & pre-compile 
    templates.

    We just will do the following : 

     

     

     


    This is all that you require in the Maven pom.xml to configure this plugin that does all the magic of downloading & installing Node & NPM, running grunt tasks. 
    Note: You can either run it in the prepare-package phase or the generate-sourcesphase. All these are placed under the <plugins> of the pom.xml. Execute Maven via the mvn clean install -DMaven.test.skip=true

    The project structure before the change:

    Now we include the plugin, note the following things in the plugin:
    <nodeVersion> : mention the required Node version. If not mentioned, the plugin picks the latest one. 
    <npmVersion> : mention the required NPM version. If not mentioned, the plugin picks the latest one.

    Yeh! But, where did you mention the dependencies for grunt ? - Its all in thepackage.json file placed directly in the root directory of the project (see above image). The contents of which is :

    Also, the gruntFile.js  which holds the grunt Tasks for this project is also placed in the root directory of the project. The idea is, the root package.json, the gruntFile.js and the pom.xml have to be on the same level.

    After the plugin is included, the folder structure is modified as this:
    Notice the Node & Node_Modules folder. The plugin downloads Node & installs NPM all under the root project folder ${project.basedir}. The former has the Node JS executable and the later has all the Node Modules required. This file mentions all the dependencies that must be downloaded by NPM. These dependencies are downloaded by NPM and placed in the Node Modules folder. 

    Now, the registered Grunt Task in the GruntFile.js (barebone sample implementation) below, is run. This has 3 tasks:

    • A simple JS Lint check of a file, 

    • pre-compiling Templates into Require AMD modules & 

    • executing the r.js optimizer to run a build on all the AMD require JS files, concatenate, compress & uglify it.

    Note : This task can be registered externally and also called. For sake of ease, it has all been posted here. The DEV & prod versions represent minified & un-minified files that will be run based on env variables of maven.

    The node installation, NPM installation, Grunt Task execute as part of the maven build cycle. The above sample was done in a JSF based project. Since the changes are only onto the POM.xml, this can be easily ported to a JSP based project or any JAVA based web-app. The console log of the maven build process capturing this phase is :
    Look at a template sample, before & after compilation. By doing this in the build time, it prevents the need to parse this template, every time before rendering. Now we just have to pass the data context and the template function renders it. Pre-compiling is converting a template to a JS function.

    We have thus completed Linting, pre-compiling of templates, generating the built file from the r.js optimizer. The pre-compiled templates have also been bundled out, along with the built file. What require JS & the r.js optimizer does reserves a separate post totally! There are umpteen more things that can be done by this setup of Node & NPM in a JAVA & Maven world, for the presentation engineering of a web app - as mentioned in the advantages above. 

    Patching changes:
    Now, in a Node world, modifying JS files and letting grunt watch over the changes & patch them to the built files isn't a problem. But what about here ? The r.js optimizer or any other optimizer for that matter, has to run its Grunt Task & re-build all the JS files., in case changes are made to a file. This will happen only if the Maven build is triggered once more & the incremental build of Maven (on making changes) includes this plugin. Even if it does, the Front End maven plugin must be able to pick those changes and only execute them. The plugin does it! The plugin observes files under the <srcDir> and refreshes built / optimized / generated files in the <outputDir>. This saves a lot of Dev effort as well, preventing the needless server re-starts.

    Where does require JS come in picture ?
    By using require JS, we have modularized the code. By using r.js optimizer, we have compressed the scripts from 450+KB to 217KB in the project we did. Further, apart from compressing, minifying & obfuscating the code, it concatenates all the scripts into one single build file. This reduces the number of http requests thereby improves the speed of rendering.



    转载本站文章《php和jsp项目的前端工程一体化!》,
    请注明出处:https://www.zhoulujun.cn/html/tools/Bundler/grunt/2016_0411_7750.html