Churn Webpack+gulp Use Posture ~

Source: Internet
Author: User

With the development of front-end technology, the mv* framework has sprung up-and many front-end building tools have been sought after.

Today, let's say Webpack + Gulp to achieve the front-end engineering posture Bar (self-feeling this posture is not good enough, you have a better posture to tell!) )

What is Webpack?

Https://github.com/webpack

  Webpack is a module loader, in Webpack, all the resources are used as modules (JS, CSS, pictures, etc.). corresponding to different file type resources, webpack have corresponding module loader to parse them (CSS has style-loader, Css-loader, Less-loader). Support is also available for COMMONJS and AMD.

What is Gulp?

Gulp is a flow-based automation build tool.

Let's take a look at the directory structure.

SRC is our source file, Gulpfile.js is Gulp configuration file, Webpack.config.js is webpack configuration file. Entrys is all the JS entry files. Dist is our goal file is the final auto-generated stuff is put here oh.

Here we use Webpack to our JS for an analysis (such as es6 ah, less ah, sass AH) and packaging processing. Webpack configuration file can be named Webpack.config.js by default, let's take a look at the configuration.

  

varWebpack = require (' Webpack '),//dependency IngestionFs=require (' FS ');varEntrypath= "./src/entrys"; varOutputpath= "./dist";//The Loop Entry folder reads the Portal filevarentrys= Fs.readdirsync (Entrypath). Reduce (function(o, filename) {/\.js$/g.test (filename) &&(O[filename.replace (/\.js$/g, ')] = entrypath+ '/' +filename); returno; }, {});//entrys[' vendors ']=[' vue ']//some common vue ah et cetera. Module.exports={Entry:entrys,//Entry Fileoutput:{Publicpath:"/dist",//the corresponding domain name, such as "http://localhost"Path:outputpath,//destination FolderFileName: ' Oldjs/[name].js ', Chunkfilename:'/chunks/[hash]. [Name].chunk.js '//Some asynchronous loading will be packaged here.}, Resolve: {extensions: [', '. js ', ' jsx ', ' vue ',//is a file suffix that can be ignored, such as direct require (' Header '), instead of adding. js. }, module:{loaders: [//The module parser that is dependent on{//ES6 after all, the browser can not parse ES6 so need to parse into ES5 first only use this slightly. Test:/\.js$/, Loader:' Babel ', query: {presets: [' Es2015 ']                }            },            /*{//parse less test:/\.less$/, Loader: ' Style-loader!css-loader!less-loader '}, Use!            To chain loaders {//Parse CSS test:/\.css$/, Loader: ' Style-loader!css-loader ' }, {//web font library or something. Test:/\. (Woff|svg|eot|ttf) \??. *$/, loader: ' url-loader?limit=50000 '}, {//Picture ha Test:/\. ( png|jpg) $/, loader: ' url-loader?limit=8192 '}//inline base64 URLs for <=8k images, direct U RLs for the rest*/]}, plugins: [//kills the compilation upon an error.        //This keeps the outputed bundle **always** valid        NewWebpack. Noerrorsplugin (),//this uses UGLIFYJS to compress your JS code        NewWebpack.optimize.UglifyJsPlugin ({minimize:true}),        NewWebpack.optimize.CommonsChunkPlugin (' Vendors ', '/js/vendors.js ')    ]}

Here we define a simple portal file in Src/entrys/hello.js, as well as an asynchronous loaded JS file Src/js/require1.js

Hello.js:

varA = []; for(vari = 0; I < 10; i++) {A[i]=function() {console.log (i); };} a[6] ();//Ten//ES6 so the Babel loader is required to parse let only valid in block-level scopesvarA = []; for(Let i = 0; i < ten; i++) {A[i]=function() {console.log (i); };} a[6] ();//6Document.onclick=function(){//asynchronous loading Oh that's require.js will be packaged into Chunk****.jsRequire.ensure (['.. /js/require1.js '],function(require) {varA = require (".. /js/require1.js ");    Console.log (a); });}

Require1.js:

Console.log (' dddd '); Module.exports={    ' a ': ' 111 '}

An HTML file referencing the corresponding js,src/html/hello.html

<! DOCTYPE html>

And then we execute webpack.

This generates a vendors.js common JS, our portal hello.js, and a chunk.js that we load asynchronously

Then we built the automation through gulp, and his configuration could be put in gulpfile.js by default, no nonsense on the code.

varGulp = require (' Gulp ')), Webpack= Require (' Webpack '), MD5= Require (' Gulp-md5-plus '), Gutil= Require (' Gulp-util '), clean= Require (' Gulp-clean ');//Clean up filesvarWebpack_config=require ('./webpack.config.js ');//get the Webpack configurationvarDevcompiler =Webpack (webpack_config);//executing a packaged streamGulp.task (' Build ',function(callback) {Devcompiler.run (function(err, stats) {Gutil.log ("[Webpack:build-js]", stats.tostring ({colors:true        })); Callback ();//Executes the next stream after execution    });});//Add JS to the 10-bit MD5 and modify the reference path in the HTML, which relies on Build-jsGulp.task (' Md5:js ', [' fileinclude '),function(done) {GULP.SRC (' Dist/oldjs/**/*.js '). PIPE (MD5 (Ten, ' dist/html/**/*.html '). Pipe (Gulp.dest (' Dist/js '). On (' End ', done);});/*gulp.task ("clean", [' md5:js '], function (done) {gulp.src ([' Dist/js ') "). Pipe (Clean ()). On (' End ', Don e);});*///put the HTML file in the DistGulp.task (' Fileinclude ', [' Build '],function(done) {GULP.SRC (' Src/html/**/*.html '). Pipe (Gulp.dest (' Dist/html '). On (' End ', done);}); Gulp.task (' Watch ',function(done) {Gulp.watch (' src/**/* ', [' Build ', ' fileinclude ', ' Md5:js ']). On (' End ', done);}); Gulp.task (' Dev ', [' Build ', ' watch ', ' fileinclude ', ' Md5:js ']); Gulp.task (' Default ', [' Build ', ' fileinclude ', ' Md5:js ']);//production environment to replace MD5 and so on do not engage in ~ ~;

The code is also clear, is to get the Webpack configuration, then execute the webpack command, and then generate the portal JS MD5 and replace the JS reference in the HTML. In the final development environment, the SRC folder is monitored, and a change is performed again.

This is my use posture, if there is a better posture please tell me oh.

Related articles: 1190000003969465

Http://www.jianshu.com/p/8c9c8f5649c9

Item Git:https://github.com/zjb65532788/webpack_gulp

PS: Daily Record a little bit, daily progress a little ~ ~

  

Churn Webpack+gulp Use posture ~

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.