Webpack Usage Summary

Source: Internet
Author: User
Tags postcss

has already translated an article about Webpack, that is just beginning to learn Webpack reference Nanyi of the tutorial, by the way, the English article to translate it over. Webpack is a powerful modular packaging and build tool that not only can package JS, but also through the loader to the CSS, image, font packaging, reference directly as a module to reference, Finally unified packaging into a bundle.js file to output, while Webpack also support plug-in features, its various plug-ins greatly enrich the Webpack function, such as the most common Html-webpack-plugin plug-in, can be written by the template in the compilation directly after compiling the required HTML page, easy to maintain , expand, and deploy on-line. In addition, Webpack can also preprocess the CSS, such as using Postcss-loader in the Autoprefixer, Pxtorem and other functions to achieve CSS-free prefix, PX automatically converted to REM; use Less-loader, Scss-loader directly references less, scss files, using CSS modules in Css-loader to implement the local and global writing of CSS styles and naming them with hash values, so that you don't have to worry about naming when you write code ... In short, webpack give a person with the feeling of omnipotent, but get started trouble, configuration items seem to let a novice face, far less than gulp small and dexterous, should also be a disadvantage of it!

Because there are too many pits in the webpack, so I will make a summary of the usage I know at this stage, and then gradually perfect the follow-up study.

One, configuration file

The configuration file is mainly divided into the import file processing, output processing, loader, plug-in, webpack Development server parts, because Webpack development Server This part of the content, put in detail in the back.

1 varWebpack = require (' Webpack '));2 varPath = require (' path ');3 4 //_dirname is the absolute path to the directory where the current module file resides5 //path.resolve equivalent to _dirname + build for address stitching6 varBuildPath = Path.resolve (__dirname, "build");7 varNodemodulespath = Path.resolve (__dirname, ' node_modules ');8 9 varAutoprefixer = require (' autoprefixer '));Ten varPx2rem = require (' Postcss-pxtorem ')); One varPx2remopts = { Arootvalue:100, - propwhitelist: [], - }; the  - varHtmlwebpackplugin = require (' Html-webpack-plugin ')); -  - varConfig = { +  -     //Portal File Configuration + entry:{ A         //Portal File path atIndex:path.resolve (__dirname, ' src/main.js ')), -  -         //to optimize, cut code, extract third-party libraries - Vendor: [ -' React ', -' React-dom ', in' React-router ' -         ] to          + }, -  the resolve:{ *         //extentions: Configuration file extension, when in import file, do not need to add extension $         //the default extension is ["", ". Webpack.js", ". Web.js", ". js")Panax Notoginseng         //an empty string is here to resolve some expressions without a file name extension in an import file -Extentions:["", "JSX", "JSON", "JS", "Web.js"], the  +         //path aliases, lazy cancer gospel A alias:{ theApp:path.resolve (__dirname, ' Src/js ')), +           //previously you might have quoted import {Nav} from '. /.. /components ' -           //Now you can quote import {Nav} from ' App/components ' $  $Style:path.resolve (__dirname, ' src/styles ')) -           //previously you might have quoted @import ". /.. /.. /styles/mixins.scss " -           //Now you can quote @import "STYLE/MIXINS.SCSS" the         }           -     },Wuyi  the     //configuration of file export - output:{ WuPath:buildpath,//Output Path -FileName: "App.js"//Output File name About     }, $  -     //generate Source-map to facilitate debug by developers -Devtool: ' Eval-source-map ', -  A module: { +         //Loaders Loader the Loaders: [ -             //Babel ES6 Analysis $             { theTest:/\. (JS|JSX) $/,//use regular to verify the name of the file suffix you want to test theInclude: [Path.resolve (__dirname, "Src/app")],//The path to the file to be processed theExclude: [Nodemodulespath],//exclude directories that are not processed the                 //Loader's name, between different loaders with! Connection? To use the functionality that comes with the loader, the loader executes as a forward -Loader: ' Babel ' in             }, the                                       the             //Image Parsing About             { theTest:/\. (png|jpg) $/, theLoader: ' url-loader?limit=50000 ' the             }, +             //CSS File parsing -             { theTest:/\.css$/,BayiLoader: "Style-loader!css-loader!postcss-loader" the             } the  -         ] -     }, the  the     //POSTCSS Platform the     //the prefix-free feature and PX conversion to REM function are configured here thePOSTCSS: [Autoprefixer ({browsers: [' last 2 versions ')]}), Px2rem (px2remopts)], -  the plugins: [ the  the         //optimizing the use of modules94         NewWebpack.optimize.OccurrenceOrderPlugin (), the         //WEBAPCK will give the compiled code fragment an ID to distinguish the         //This plugin allows Webpack to optimize and maintain consistency on the ID assignment.  the         //Specifically, the optimization is: Webpack can be compared to the use of ID frequency and distribution to derive the shortest ID assigned to the module with high frequency98  About  -         //Compress Code101         NewWebpack.optimize.UglifyJsPlugin ({102 Compressor: {103Warningsfalse104               } the         }), 106 107 108         //Remove Debug Prompt information109         //Many libraries have a process in the interior. Node_env's judgment statement, the         //change to production. The most intuitive is not all the debug related things, the volume will reduce a lot111         NewWebpack. Defineplugin ({ the' Process.env ': {113' Node_env ': json.stringify (' production ')) the               } the         }) the 117 118         //' Vendor ' is to pack all the dependent libraries (such as React React-router, redux) into Vendor.js119         //"Vendor.js" is to write their own relevant JS packaged into the Bundle.js -         //generally rely on the library to put in front, so vendor put the first121         NewWebpack.optimize.CommonsChunkPlugin (' Vendor ', ' Vendor.js ' ),122 123 124         NewHtmlwebpackplugin ({ theTemplate: ' src/index.html ',126               //path to the HTML template127                -Title: ' Product model ',129               //the title of the HTML template the               131FileName: ' index.html ', the               //filename and where the file will be stored133 134Favicon: './src/favicon.ico ',135               //Favicon Path136               137Inject: ' Body ',138               //js Insert position, true/' head ' false/' body '139  $Chunks: [' Vendor ', ' Index ' ],141               //Specifies the introduced chunk, which, based on the entry key configuration, will introduce resources for all pages without being configured142 143Hashtrue,144               //so each client page will be based on this hash to determine whether the page is necessary to refresh145               //in the project follow-up process, often need to make some changes update what, one but there are changes, the client page will be automatically updated! 146 147 minify:{148               //Compress HTML files149Removecomments:true, Max                 //Remove comments from HTML151  theCollapsewhitespace:true153                 //remove whitespace and newline characters154               }155         })156     ]157 }158 159module.exports = config;

The above code details the usage of webpack and the commonly used loaders and plugins in the actual project development process.

Second, start the operation

Webpack How to start running the compilation, there are several main methods:

1. Start the compilation

Webpack    //  default execution of webpack.config.js file
Webpack--config webpack-pro-config. js
Webpack--display-error-details
Webpack--watch
Webpack-p
webpack-d //Generate map Map file to tell which modules were eventually packaged

2. Quick execution

When we want to execute the webpack command, we have to enter a long walk in the command line command, it is inconvenient to operate, but also does not facilitate the maintenance of subsequent personnel, We can write the Execute command in the scripts key in the Package.json file, so that each time we execute we just need to tap the custom command.

"Scripts": {    "start": "Webpack--watch",      //  npm start      "Dev": " Webpack-dev-server--host 0.0.0.0 ",    //  npm run dev    " pro ":" Webpack--config Webpack-pro-config.js--progress--colors "   //  npm Run Pro  }

Webpack each loader and plug-in usage details:

1. The last time I translated the Webpack-demo

  

  

Webpack Usage Summary

Related Article

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.