Webpack Build Tool Quick Start Guide

Source: Internet
Author: User
Tags base64 npm scripts

Recently in the study of the React project, access to webpack packaging tools. Just contact when a blank face, after the recent study, I will take you to open the Webpack introductory journey.
What is Webpack?

Webpack is the most recent one of the most fire module loader and packaging tools, it can be a variety of resources, such as JS (including JSX), style (including less/sass), pictures and so on as a module to use and processing. When Webpack processes an application, it constructs a dependency graph recursively (dependency graph), which contains each module that the application needs, and then packages all of them into a small bundle-usually only one, which is loaded by the browser. Of course do react project can also not webpack build tools, can use Gulp or grunt and other building tools, but GitHub above rect related projects are built with Webpack, the official recommendation is webpack more appropriate, so we have no reason not to master it.

The way Webpack works is to treat your project as a whole, With a given portal file (for example: Index.js), Webpack will start to find all dependent files for your project from this file, use loaders to process them, and finally package it up as a browser-aware JavaScript file.

Advantages of Webpack
    1. Everything in Webpack seems to be a module, including JavaScript, CSS, and pictures.

    2. Development is convenient, can replace part of the work of GRUNT/GULP, such as packaging, compression confusion, picture turn base64, etc...

    3. Strong extensibility and perfect plug-in mechanism.

Webpack file Configuration

Webpack has four core concepts: ingress (Entry), output, loader (loader), plug-in (plugins). Here's a look at the Webpack.config.js file

Const WEBPACK = require (' Webpack ');
Const Extracttextplugin= Require (' Extract-text-webpack-plugin ');//CSS Separate package pluginModule.exports= {    //Page Entry Fileentry: {app:'./src/app '    },    //package file Output configurationoutput: {path:' Dist/js ',//Package Output PathFileName: ' [name].min.js ',//file name    },    //The automatic extension of the file suffix means that we can omit the no-write suffix name in the Project import moduleResolve: {extensions: ['. js ', '. Jsx ']    },    //Module Loader (picture/js/css/, etc.)module: {rules: [{test:/\. (JS|JSX) $/, exclude:/^node_modules$/, use: [{loader:' Babel-loader ', Options: {presets: [' es2015 ', ' react '], plugins: ["Transform-object-rest-spread"]}}]},{test:/\.less$/, exclude:/^node_modules$/, Loader:ExtractTextPlugin.extract ({fallback:' Style-loader ', use:' Css-loader!less-loader '})}, {test:/\. (png|jpg|gif) $/, exclude:/^node_modules$/, Include:path.resolve (__dirname,'./img '), Loader:' Url-loader ', Options: {limit:8192//image file less than 8kb direct to Base64            }        }]    },    //plug-in items (here in one CSS separately packaged, otherwise the CSS file will be packaged with the JS file)plugins: [NewExtracttextplugin ("Styles.min.css")    ]}
Production Environment Webpack.prod.js Configuration

Webpack comes with UglifyJsPlugin it, it runs uglifyjs to compress the output file.

//Webpack.prod.jsConst WEBPACK = require (' Webpack '); Const Htmlwebpackplugin= Require (' Html-webpack-plugin ') Module.exports= {      /*...*/      Newwebpack.optimize.UglifyJsPlugin ({output: {comments:false //Delete a comment}, Compress: {warnings:false //do not display a warning, default is False            }        }),        NewHtmlwebpackplugin ({//generate final HTML based on template insert Css/js, etc.FileName: ' build/',//generated HTML storage pathTemplate: './src/template/index.html ',//HTML template pathHashtrue,//generate hash values for static resource CSS files and JSTitle: ' Pocket ', Favicon:'./img/favicon.ico ', inject:true,//All JS resources are placed at the bottom of the bodyminify: {removecomments:true,//Remove CommentsCollapsewhitespace:true,//Remove SpacesMINIFYCSS:true,//compress css in HTMLMINIFYJS:true //compress the JS in HTML            }        }),};

Html-webpack-plugin plug-in details please see (https://www.npmjs.com/package/html-webpack-plugin)

Installation method

$ NPM Install Webpack-g

Run Webpack

Webpack--display-error-details The back parameter "--display-error-details" is recommended, which makes it easier to locate problems when errors occur. Other key parameters are:

$ webpack--watch//monitor changes and automatically pack

$ webpack-p//Compression obfuscation script

$ webpack-d//Generate map Map file to tell which modules were eventually packaged

Let's add a NPM script to start Webpack:
Package.json

{    "Name": "Demo",    "Version": "1.0.0",    "description": "",    "Main": "Webpack.config.js",    "Scripts": {      "Test": "Echo \" Error:no test specified\ "&& exit 1",      "Dev": "Webpack-dev-server--config webpack.config.js--inline--hot",      "Build": "Webpack--config webpack.prod.config.js"    },    "keywords": [],    "Author": "",    "License": "ISC",    "Devdependencies": {      "Css-loader": "^0.28.4",      "Csv-loader": "^2.1.1",      "File-loader": "^0.11.2",      "Html-webpack-plugin": "^2.29.0",      "Style-loader": "^0.18.2",      "Webpack": "^3.0.0",    }  }

How to run the development environment

Using webpack-dev-server development Services is a better choice. Webpack-dev-server is a small node. JS Express server that will launch an express static resource Web server and will automatically run Webpack in listening mode, open in the browser http://localhost : 8080/(port number Configurable) you can browse the pages in the project and the compiled resource output, and monitor their changes in real time through a Socket.io service and refresh the page automatically.

One thing to note is that the package generated by the Webpack-dev-server startup project is not placed in your real directory, but is in memory and you can see it from the source panel in the Chrome browser.

Now we can run NPM start on the command line and we'll see the browser loading the page automatically. If you modify and save any source file now, the Web server will automatically reload the compiled code. Give it a try!
Production environment Operation Method

Start a project using NPM run Build

Not familiar with NPM scripts, please find Miss Ruan's article [http://www.ruanyifeng.com/blog/2016/10/npm_scripts.html]

Based on the Webpack guidelines to write here, if you look after you can let a face of the vacant you suddenly enlightened, you can ask me to drink coffee, you can also refer to the following article to get started:

[Http://zhaoda.net/webpack-handbook/install.html]
[http://webpack.github.io/docs/]

Webpack Build Tool Quick Start Guide

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.