Webpack practiced Hand project: Easyslide (i)

Source: Internet
Author: User

Recently in learning Webpack, just took a small component before doing, picture Carousel to do the next practiced hand, let us together to initially feel the magical charm of webpack.

Webpack is a front-end packaging management tool, you can go to: http://webpack.github.io/for detailed understanding. Compared to the previous front-end Module packaging tool,

Personally think that Webpack has at least one of the following merits that we can use:

    • Js/css/img/html and so on are all static resources, can be packaged and processed by Webpack
    • All resources can be loaded on demand, eliminating the need for the previous loader to package all resources in one file, resulting in large files and unnecessary modules being loaded, as well as avoiding the ability to package resources in separate files, resulting in a large number of HTTP requests resulting in reduced page performance
    • Provide a lot of front-end packaging needs of the supporting widgets, such as: JS compression, Jshint, image compression and so on
    • Perfectly compatible with AMD and COMMONJS as well as the ES6 syntax, the modules you wrote earlier don't have to be re-engineered.

There are many advantages that I have not mentioned or have not yet learned, but for the moment these advantages can be fully satisfied with our actual packaging requirements in the project.

This is the Webpack module package with a previous article: Http://www.cnblogs.com/souvenir/p/4977407.html mentioned in the picture carousel together, and share with you.

1. Watch the demo first

Similarly, this time I also will write the demo code to share on GitHub, you can go to view Source: https://github.com/xiaoyunchen/easySlide/

The final page effect can be accessed by http://xiaoyunchen.github.io/easySlide/for viewing.

The function is simple:

As you can see, we made two picture carousel on this page, and the time interval of two images and the animation duration are independent and non-interfering with each other.

    

2. Preparatory work

Before we begin to learn webpack packaging, we need to do some preparatory work first. The first step, of course, is to install Nodejs, and then use the NPM command to install Webpack and the few loaders we need:

NPM Install Webpack-gnpm Install [email protected]1npm install CSS-loadernpm install style- Loader

3.webpack Packaging

After watching the final effect, we'll go on to see how this simple project is packaged using Webpack.

First of all in GitHub you can open the project's source code, you can see the project directory structure is this:

    

The outermost layer has several files:

Index.html---Project entry page

Package.json files for describing the structure of a module package---the NODEJS environment

Webpack.config.js---webpack configuration file, we'll focus on this profile later

Then there are three directories:

SRC---Source code for project development

Node_modules node module for---project packaging

Dist---The final output directory after packaging

Then take a look at the structure of the SRC directory, first according to the regular Css/js/img division, and then each directory in accordance with the function module sub-directory Division:

Module---generic components

Page---pages app

Vendor---Referencing third-party components

This is my personal directory division, the actual project can be based on the project or the needs of the company to adjust.

Then look at the entry file: Index.js

1(function(){2     //introduction of public CSS and page CSS3Require ('.. /.. /css/vendor/reset.css ');4Require ('.. /.. /css/page/index.css ');5     6     //introduce and create multiple standalone slidemodule modules7     varSlidemodule=require (".. /module/slide.js ");8     NewSlidemodule ({dom:$ (' [node-type= ' Iccadvisorpicture "])});9     NewSlidemodule ({Tendom:$ (' [node-type= ' iccAdvisorPicture2 '] '), Onedelay:4000, Aduration:800 -     }); -})();

The code volume of 14 lines, overall is relatively refreshing, which is due to the module packaging.

Here, we define and execute a closure function. The main function is two:

1. Load the public CSS on the page (don't forget that CSS is also a resource that we can load by Webpack)

2. We have introduced a custom slidemodule component and then created two instances of the picture carousel using the component

is so concise, this is what we want, the function according to the module development, the use of the time as needed to load.

Let's take a look at the Webpack configuration file, regardless of how the Slidemodule is specifically implemented:

1 varPath=require (' Path ');2 varWebpack = require (' Webpack '));3Module.exports = {4 entry: {5Index: "./src/js/page/index.js",6         },7 output: {8Path:path.join (__dirname, ' dist ')),9FileName: "Bundle.js"Ten     }, One module: { ALoaders: [//CSS Loader -{test:/\.css$/, Loader: "Style!css" } -         ] the     }, - plugins:[ -         NewWebpack. Provideplugin ({//Load JQ -$: ' jquery ' +         }), -         NewWebpack.optimize.UglifyJsPlugin ({//Compress Code + Compress: { AWarningsfalse at             }, -except: [' $super ', ' $ ', ' exports ', ' require ']//Exclude Keywords -         }) -     ] -};

For detailed parameters and attributes in this configuration file, you can go to Webpack website to view them. Here we mainly explain the purpose of this configuration file to achieve.

Entry: entrance. Note that the path here is relative to the webpack.config.js path, which is the root directory

Path: The main definition of the packaged file directory and file name, here we are the packaged files in the/dist/bundle.js file.

Module-loaders: Loader. Here we only use a CSS loader

Plugins: Plugin. The first is jquery, we load jquery into the project and return $ as a global variable, so jquery can be used anywhere and without additional configuration.

The second is the output of the JS code compression, this step is optional, it is generally possible to have a deployment server will be deployed to the formal environment before the compression processing.

OK, Next we can use Webpack to package, switch the directory where the current project is located at the command line, and then package the use:

Webpack-w

You can then only see the output similar to, without any error, that the package has been successful:

  

-W is the package option, watch meaning, Webpack will monitor the project's files if there are changes, the packaging command will be run automatically

Other options are:-P compression code. But generally we will compress the code in the Unload configuration file.

-D Output Sourcemap

After the package is successful, we only need to introduce/dist/bundle.js in the Index.html page, and even the CSS will not need to be introduced.

You can then run the page to see the specific effect.

Ok,webpack packaging process is probably the case, I believe you may have some questions, this is not to put all the resource files in a file, if the project is too large, then the file is not very large.

Here's what we said earlier Webpack can implement on-demand loading modules, we will introduce you in the next article.

  

4.slideModule Module

Next we look at how the image carousel is implemented and how the implementation process uses the Webpack syntax for resource loading.

       

This is our code, all the code is also in a closure function, this can avoid the global variable window pollution.

Line 2nd We use require introduced a CSS file, this CSS is specifically belong to the Picture Carousel module, introduced in the module, the implementation of the mask, the outside of the JS in use no longer care is not to be in

The introduction of additional CSS requires only one sentence to be introduced and then the corresponding function is completed.

Line 4th defines a default configuration object that defines some of the basic configuration of the module, which we will use by default if we do not pass in the corresponding parameters at the time of use.

The 12th line defines a method, which is actually the building function of our image sliding module, in which we first merge the outer-pass configuration parameters with the default parameters.

Then recalculate the number of pictures based on the DOM selector.

In line 19 we use prototype to extend the method of slidemodule, adding several processing methods

1Slidemodule.prototype={2Init:function(){3                  This. Bindmouseevent ();4                  This. AutoPlay ();5             },6Slidepic:function(){//Toggle Picture7                 varthat= This;8                  This. config.dom.animate ({' MarginLeft ':-( This. config.current== This. config.total?0: This. config.current) * This. config.width+ ' px '}, This. Config.duration,function(){9that.config.current++;Ten                     if(that.config.current>that.config.total) { OneThat.config.current=1; A                     } -                 }); -             }, theAutoPlay:function(){//Automatic Switching -                 varthat= This; -                  This. Config.timer=setinterval (function(){ - that.slidepic (); +}, This. Config.delay); -             }, +Bindmouseevent:function(){//bind mouse Move in/Remove events A                 varthat= This; at                  This. Config.dom.mouseenter (function(){ -                     if(that.config.timer) { - clearinterval (that.config.timer); -                     } -                 }); -                  This. Config.dom.mouseleave (function(){ in That.autoplay (); -                 }); to             } +};

Init: module initialization method, which is responsible for invoking the corresponding function to initialize the module function.

Slidepic: The implementation of the image switch, using the jquery animate method, created an animation, the image of the outer layer of the parent element marginleft reduce the width of a picture

The duration of the entire animation comes from the configuration information.

After sliding the animation will modify the current display is the first few pictures, if the maximum number of words set back to 1, so that the next time the animation from the beginning.

AutoPlay: Create a timer that automatically executes slidepic at intervals to toggle the image, which results in automatic carousel.

The reason why the closure function is used here is because of the scope, so you can view the previous article in detail.

Bindmouseevent: Two mouse events added here, when the mouse moved into the sliding component area, clear off the timer temporarily animation, when the mouse left the timer, resume the rotation of the animation

  

The implementation of the picture carousel is probably this:

  

The outermost div width is fixed, the same as the individual picture width (loading margin), and the part of the hidden display is set at the same time, and then the UL width is set to large, at least the width of the image of N Bai, so that all the pictures can be placed on one line

Then the timer to change the UL Margin-left value, so as to achieve the effect of sliding switching.

      

    

Webpack practiced Hand project: Easyslide (i)

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.