Recent summary: Generator-web, front-end automation-built solutions

Source: Internet
Author: User
Tags php template

Based on the recent work experience, this paper summarizes a relatively concise front-end automation construction scheme, advocates the modularization of CSS and JS, and effectively solves the problems of CSS merging, JS merging and picture optimization through grunt automation, and has certain reference value for improving front-end performance and project code quality. Welcome to read and review:)

GitHub Address: Https://github.com/liuyunzhuge/generator-web

Demo Address: https://liuyunzhuge.github.io/generator-web/

Interested classmates, in the process of reading articles, learning or using the demo, have any doubts or found problems in spite of discussing with me in the comments.

1. Overview

This project is a scaffold, applied to the front and back end of the joint project, can provide the following services for this project:

    • Picture compression, support png,jpg,gif format picture
    • CSS modularity, but requires less to write CSS
    • JS Modular, requires the use of Requirejs to define the module
    • CSS compression merge, can be done to a page containing only a CSS file
    • JS compression Merge Confusion, can do a page contains only a script tag, only 2 script requests, one is Require.js, the other is page-related JS, the dependent JS are through the Requirejs optimization tool, with the page JS merged into a
    • All of these tasks can be built automatically through grunt, and during development, the compilation and file updates are triggered proactively so that you can see the latest results in a browser refresh.

The front and back end of the joint project is javaweb,asp.net this non-front and back end of a completely separate project, the page is usually jsp,aspx,php template, the deployment of the update package contains both front and back files, belonging to the traditional project type.

This scaffold application scenario is limited to the front and back end of the combined project, it can only solve the project's frontend construction work, for the back-end build and project packaging release work needs to be done by the back end, if you are javaweb type, back-end release can use MAVEN, it can complete the back-end building and packaging tasks. The reason for this scaffolding is mainly due to the current and back-end joint-type project development mode is very common, after all, not every company has the resources to achieve a complete front-end separation of this kind of architecture, especially small companies or project-based companies, not so people and time resources can let you play advanced things, Rapid development is the kingly way. However, for any Web project, the front-end part of the basic services are the same, compared to slice optimization, CSS and JS merge compression, and this is the best team resources feasible situation, for the project quality, only the benefits of no harm. The scaffolding is produced from the work of a set of development shelves, based on this shelf, you can easily get the following benefits brought to you by it:

    • CSS and JS modularity to help provide code quality for the project and facilitate future maintenance
    • Image optimization, CSS and JS compression merge, greatly reduce the amount of data requested and the number of requests, very conducive to project access performance
    • The front-end task is fully automated, without worrying about such issues as compiling and file copying, and following the conventions of this project, you will find that CSS and JS development structure is so clear
2. Structure
web-inf/HTML/img/js/less/  Gruntfile.jsbower.jsonoptimize.jsonpackage.json

Because this scaffold is released together with the demo on GitHub, the demo is based on Javaweb, so you will see there is a web-inf/folder, this is Javaweb must, html/inside the page is a JSP template, This is also necessary for javaweb, so if you want to apply this scaffold to ASP. NET and PHP you need to delete the Web-inf folder, and then change the JSP in html/to aspx or PHP template.

In addition, regardless of what type of project you want to use for this scaffold, the best way to do this is to run the demo first and then develop it on the demo basis to reduce the error.

template for storing pages (jsp,aspx,php) or HTML file img Store picture JS/ Store jsless/ store Lessgruntfile.js This is the configuration file for the grunt task Bower.json This is Bower configuration file Optimize.json This is the configuration file for the Requirejs Optimizer tool Package.json This is the grunt dependent profile

Note: html/,img/,js/,less/these three folders also have sub-folders, each have related conventions, followed by each introduction. Before the demo runs successfully, please do not change those configuration files first.

2.1 DEMO

View demo:https://liuyunzhuge.github.io/generator-web/support Ie9+,chrome,firefox.

The demo is gh-pages set up, you can see the Gh-pages branch of this project to view the file content of the demo, since GitHub provides this service only support static Web page, so the home page of the demo is actually by html/ Index.jsp transformed, another position also changed a bit, index.jsp originally was placed in html/below, Gh-pages branch of index.html placed in the same position with html/, do not do so, gh-pages can not see the effect.

3. Installation

Since this project is published in conjunction with Javaweb, the following steps are described in the Java Development environment, with the IDE as IntelliJ idea. If your project is also a Javaweb project, then it is recommended that you use this IDE, which is the best Java Web Development tool I have used and integrates many front-end tools such as Less,emmet and Grunt and bower. If you use it to develop projects, you will find that writing less and using grunt is so smooth! Pure background development may not be picky about development tools, but front-end development If you want to get together with the background, it's best to use an advanced IDE.

3.1 First Step

Install Nodejs,git,bower,grunt. Installed under Windows, no Linux required. which

    • Nodejs,git has a Windows installation package on the website
    • Bower and Grunt installations are installed via the command line, and the installation methods are referenced to their respective websites:
    • bower:http://bower.io/
    • grunt:http://www.gruntjs.net/getting-started

Note: This step has nothing to do with the IDE and the back-end language. Regardless of the language of the project, this is the basis for using this scaffold.

3.2 Step Two

Create a new Web project, such as I use idea to create a new project named Generator-web-demo, whose project structure is as follows:

. idea/src/web/generator-WEB-DEMO.IML

Among them. iead/and GENERATOR-WEB.IML are created after the project is completed, and can be used without a tube. SRC is the directory of the Java source files, and the Web folder is the Web root of the project.

3.3 Step Three

On github, download zip or clone this project with Git, copy the following folder or file of this project into your project's Web root directory (the Web folder mentioned in the previous step):

Html/img/js/less/WEB-inf/  Bower.jsonGruntfile.jsoptimize.jsonpackage.json

Web-inf directly cover the original Web-inf can be. If the original web/under a index.jsp, you can delete it, my habit is to put a piece of the page, html/has provided a index.jsp, so the original index.jsp redundant.

Finally, your project structure should be as follows:

. idea/src/web/    HTML/    img/    js/Less    /     WEB-inf/    bower.json    gruntfile.js    optimize.json    package.jsongenerator -WEB-DEMO.IML
3.4 Fourth Step

Using Bower to install libraries configured in Bower.json (Jquery,icheck,requirejs,bootstrap)

Install --save

Note: The above library in addition to Requirejs is a scaffold must, the other can be added and deleted according to the actual project needs, but in order to put the demo run up, or do not change it, understand the construction of the principle of the project needs to be modified or not later.

To install the grunt and grunt plugins:

Install --save

If NPM is slow to install, it can be installed in the same way as the following URL, which is faster: http://npm.taobao.org/

3.5 Fifth Step

To perform the default task for grunt:

Grunt Default

If the execution of grunt this task error, is generally grunt-contrib-imagemin plug-in error, you can use the following command to reload Grunt-contrib-imagemin

NPM Uninstall Grunt-contrib-imagemin--install grunt-contrib-imagemin--save

Note: The above is a two command, separate execution. If also reported is the same error, try the above command a few more times.

Finally start your Web server, such as Tomcat. Open browser access should be able to see the same as the Demo page effect:).

4. Development

This section describes how to develop on a demo basis.

4.1 Development Page

Each new page is placed under Html/, currently included in the demo:

html/   Base/      body_end.jsp      head_end.jsp      head_start.jsp   index.jsp   ltie9.html 

Where: base/is a number of public JSP page, you see the index.jsp inside those inclue you understand. Ltie9.html is a prompt page, if the user to IE8 and the following Internet Explorer Access will jump to this page prompted to update the browser or other useful browser.

If your project is an ASP. NET project, please replace these jsps with ASPX.

This html/idea is: base/put public, other pages by module, if a module has only one page, then put it directly under the html/, if a module has multiple pages, you can build a folder in the Html/module name, the relevant pages are put there.

When you develop the page, the suggestion:html/base/public JSP Reservation, the new page to index.jsp as a reference for development, you can add more public pages to the base/, you can also classify the new page by module.

The problem of 4.2 baseurl

This is the problem, for example:

    • If you use ECLISPE to develop the project, after you start Tomcat, open the browser access, you must be [http://hostname port/project name/] to access, in order to Generator-web-demo example, you must use the [http://localhost : 8080/generator-web-demo/] To access, of course, this can change, I'm here to take the general situation example
    • In the case of idea development, there is no problem with this project name, because its tomcat default configuration is the way to omit the project name, which can be accessed directly through http://localhost:8080/
    • This project name configuration is ContextPath, because the existence of this contextpath may lead to your page css,img, and script loading when the load is not loaded, so usually in the front and back of the combined project, Be sure to unify this contextpath so that all resources are loaded relative to the same path to parse.
    • The common way is to put all the resources of the URL of the ContextPath and the previous paragraph set to the HTML base element, due to the role of the base element, you can ensure that the script and CSS and image loading are relative to the base of the href attribute to parse

The base element is set with the following code: <HEAD_START.JSP>

<%    StringBase=Request.getscheme ()+ "://" +Request.getservername ()+ ":" +Request.getserverport ()+Request.getcontextpath (); Base+=Base.endswith ("/") ? "" : "/"; Request.setattribute ("Base", base); Request.setattribute ("Rnd", "? v=0.0.1");%><!DOCTYPE HTML><HTMLLang= "ZH-CN"><Head>    <MetaCharSet= "Utf-8">    <Basehref= "${base}">    <Metahttp-equiv= "X-ua-compatible"content= "Ie=edge">    <!--[If Lt IE 9]> <meta http-equiv= "Refresh" content= "0; url=${base}html/ltie9.html"/> <! [EndIf] -

When referencing CSS, images, and JS, refer directly to the path relative to the Web root directory:

<Linkhref= "Css/index.css"rel= "stylesheet"><imgsrc= "Img/dist/logo.png"alt= "LOGO"><ScriptData-main= "Js/dist/mod/index"src= "Js/dist/lib/require.js"></Script>

Remember this structure of the Web root directory:

web/    img/    CSS/    JS/
4.3 pic

The images associated with the project are placed under the IMG folder, and the structure of the img/is:

img/   Dist/   src/   temp/

This directory structure is best not to change. which

    • dist/the picture after the Grunt Picture optimization task, is also the reference path of the picture in the code
    • src/storing image source files for optimization
    • temp/according to sprite map of the original picture files of sprite, such as you make a sprite, you name it as Common.png, then in temp/inside, create a new common folder, you make sprite map of the source map used to put in, So in the future you need to adjust the sprite map from here to find the source map, sprite production recommended this tool: http://alloyteam.github.io/gopng/, use it can also be used to make your sprite map of each configuration to export to the local, next time to modify, Re-import the previous configuration to continue editing in the last state

Each additional picture or sprite, throw it into the IMG/SRC, page or CSS when referring to the picture, directly use img/dist/this path to reference.

4.4 Less

Convention CSS is written in less, the structure of the less folder is:

less/    app/       icon/       mixin/       widget/    mod /    Sprite/

which

    • app/icon/Store the font icon file, as well as the font icon less, such as if you use Iconfont, then the downloaded Iconfont font file copied to app/icon/, Save the Iconfont.css as a iconfont.less and save it in this folder.
    • app/mixin/Store Some of the definitions of less mixin,demo many mixin are extracted from the source code of bootstrap
    • app/wifdget/Store Some of the public components of less, for some public modules, such as header,footer, search box, shopping cart, etc. can be defined as a single module, which page of the use of this module, import a bit better
    • sprite/Store Sprite graph related less, when making sprite chart, gopng This tool will provide you with its generated CSS, you can save it as less, I do is to the sprite map each background map of the CSS is defined as a mixin, so that the HTML elements in the use of a brother background map, As long as the introduction of this less file, tune mixin on it, the specific way, please refer to the demo sprite/under the two less file definition, as well as the use of app/mod/index.less in the way
    • app/mod/store the page less file, basically each page a less, also by the module re-build folder to classify, with the development of new pages the same reason

Grunt Less task, will be app/icon/under the font copy to web/css/, the app/mod/under the less compiled CSS also put to web/css/, so when the page introduced CSS, relative css/this folder reference :

<href= "Css/index.css"  rel= "stylesheet">

In this piece need to pay attention to the problem is the font file and picture file path problem, remember that less compiled CSS is placed under the css/, and picture optimization is placed under the img/dist/, font files and CSS default is directly located in the css/directory, Please refer to the demo app/mod/index.less for more details.

4.5 js

The Convention JS source code are defined under js/src/, js/src/structure for

js/   js/src/       app/          mod/          widget/       lib/        MoD/       common.js

which

    • Common.js is a configuration file for Requirejs
    • js/src/mod/store main.js for each page
    • js/src/lib/Storage-dependent JS library, such as jquery,icheck,bootstrap transition will be through the grunt task, from the Bower download location copy to here, Please see Gruntfile.js's copy task, and this folder is also the location of Requirejs BaseURL.
    • js/src/app/mod/Store the actual logic of each page JS
    • Js/src/app/widget Storage component-related JS, such as the demo defines four components, Tab,carousel,icheck,radiotoggle

In the absence of optimization, the grunt task will copy all js/src/files to js/dist/, after optimization, the grunt task will be js/dist/mod/under each JS dependency of all JS, and it merged into a JS. No matter if there is no optimization, the page refers to the JS file, relative js/dist this directory reference!

A page-related JS entire loading process, in the demo index.js for example:

    • First through the page: <script data-main="js/dist/mod/index" src="js/dist/lib/require.js"></script> load Js/dist/mod/index.js
    • Since the source of Index.js is:
function (Common) {    Requirejs ([' App/mod/index ');});
    • It will load the Common.js read configuration before loading the js/dist/app/mod/index.js to execute the page's logic
    • After Js/dist/app/mod/index.js, it is the process of loading each dependent module to handle the page logic, and the entire JS asynchronous dependency and load situation is over.

So develop a JS step for, suppose to develop a usercenter.js:

    • First create a new usercenter.js under the js/src/mod/
    • Create a new usercenter.js under the js/src/app/mod/
    • Change the source of Usercenter.js under Js/src/mod to:
function (Common) {    Requirejs ([' App/mod/usercenter ');});
    • Because js/src/mod/under the JS are only a bridge, so this folder each JS is only three lines.
    • Write your page logic in Js/src/app/mod/usercenter.js

In addition, add a configuration item to the Usercenter.js in the Optimize.json so that the production environment can be built with the JS that it relies on to merge it into a JS.

4.5.1 How to configure Optimize.json

Simply put, this template will do the following:

[    {        "name": ". /mod/index ",        " include ": [            " App/mod/index "        ]    }]

For example, if usercenter.js, then it should be configured as:

[    {        "name": ". /mod/index ",        " include ": [            " App/mod/index "        ]    },    {        " name ":". /mod/usercenter ",        " include ": [            " App/mod/usercenter "        ]    }    ] 

Specific principles involved in more details, you can refer to the following two URLs to study:

    • Http://www.requirejs.cn/docs/optimization.html
    • Https://github.com/requirejs/example-multipage
5. Build 5.1 development environment
Default

Using the above tasks will start the build, including:

    1. Optimize the picture and store the optimized picture to img/dist/
    2. Compile the less under Less/mod and store it to css/
    3. Copy the font file under Less/app/icon to css/
    4. Copy all the contents of the js/src/to js/dist/
    5. Monitor the changes of files within the img/src/,less/,js/src/, and automatically perform the corresponding

This build does not compress CSS and does not combine compression to confuse JS.

5.2 Production environment
Grunt Release

Use the above tasks to complete the production environment construction:

    1. CSS compression on the basis of development environment construction
    2. Use the Requirejs optimization tool to optimize the page JS, the module it depends on all merged into a JS, and do compression obfuscation processing
5.3 Optimize
Grunt optimize

This task can be used to test whether the merge of Requirejs is correct and is actually used as follows:

    • Execute grunt default First
    • Re-execute grunt optimize
    • Look at the JS under js/dist/mod/, refresh the browser under test function

The reason for not merging with the default task is because the optimization task is time-consuming and does not need to be optimized for each development

6. Packaging

Before packaging, execute and grunt release commit the modifications to the code server. In addition Bower_components and node_modules these two folders do not upload to the code server up, front-end use of things, packaging backstage colleagues how will you do this, but also remember to remind them to remove the following folders from the project:

img/src/img/temp/js/src/Less/

There is no need to publish these files. As for the specific how to pack, is the responsibility of the back office colleagues.

7. Planning

Currently known unresolved issues:

    • Requirejs Asynchronous Load JS when the cache is particularly serious, the current development environment can be configured Requirejs Urlargs resolution, but the production environment when this urlargs to be removed, in js/src/ Common.js can be removed, the next step should be done grunt release mission
    • Static resource update issues, such as JS and CSS updates, but the client also has a cache
    • Automatic base64 encoding of picture and font files

The next step is to solve these problems.

Recent summary: Generator-web, front-end automation-built solutions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.