Webpack Getting Started learning

Source: Internet
Author: User

1. What is Webpack?

Webpack can be seen as a modular baler: The thing it does is to analyze your project structure, find JavaScript modules and other extension languages (Scss,typescript, etc.) that the browser cannot run directly, and package them in the appropriate format for use by the browser.

What are the characteristics of 2.WebPack compared to grunt and gulp?

In fact, Webpack and the other two do not have much comparability, gulp/grunt is a tool to optimize the front-end development process, and Webpack is a modular solution, but webpack the advantages of Webpack can replace gulp/ Tools for the Grunt class.

Grunt and gulp work in a configuration file that indicates specific steps for tasks such as compiling, combining, and compressing certain files, which can then be done automatically for you.

Workflow for Grunt and gulp

The way Webpack works is to treat your project as a whole, With a given master 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 as a browser-aware JavaScript file.


Getting Started with Webpackafter a preliminary understanding of how Webpack works, we begin to learn to use webpack step-by-step. installationWebpack can install with NPM, create a new empty Practice folder (named Webpack Sample Pro), and execute the following instructions after the terminal is transferred to the folder to complete the installation.
Global Install NPM install-g webpack//install to your project directory NPM install--save-dev Webpack
Preparations for the formal use of Webpack 1. Create a Package.json file in the Practice folder above, a standard NPM documentation that contains a wealth of information, including the current project's dependencies, custom script tasks, and more. Use the NPM init command in the terminal to automatically create this Package.json file
NPM Init

After entering this command, the terminal will ask you a series of information, such as project name, project description, author and so on, but don't worry, if you are not ready to publish your module in NPM, the answer to these questions is not important, enter the default.

1.package.json file is ready, we install Webpack as a dependency package in this project

Installing WEBPACKNPM install  --save-dev webpack

2. Go back to the empty folder and create two folders in it, app folder and public folder, app folder to store raw data and JavaScript module we will write, The public folder is used to store data that is ready for the browser to read (including the packaged JS file generated using Webpack and a index.html file). There are also three files that need to be created here, the. index.html file is placed in the public folder, and two JS files (greeter.js and main.js) are placed in the app folder, as shown in the project structure

index.html file has only the most basic HTML code, its only purpose is to load the packaged JS file (bundle.js)

<! DOCTYPE html>

Greeter.js only includes a function that returns an HTML element that contains a greeting message.

Greeter.jsmodule.exports = function () {  var greet = document.createelement (' div ');  Greet.textcontent = "Hi there and greetings!";  return greet;};

The main.js is used to insert the node returned by the Greeter module into the page.

main.js var greeter = require ('./greeter.js ');d Ocument.getelementbyid (' root '). AppendChild (Greeter ());
Official use of Webpack

Webpack can be used in the terminal, its most basic command is

file/入口文件} {destination for bundled file/存放bundle.js的地方}

You only need to specify a portal file, Webpack will automatically identify other files that the project depends on, but be aware that if your webpack is not installed globally, you will need to specify an additional address in the node_modules when you use this command in the terminal, and continue with the example above , the following command is in the terminal

//webpack非全局安装的情况node_modules/.bin/webpack app/main.js public/bundle.js

The results are as follows


TermialResult1


It can be seen that Webpack also compiled main.js and Greeter,js, now open index.html, you can see the following results


HtmlResult1


There is no excitement, has successfully used Webpack packaging a file. However, if it is not convenient and error-prone to perform complex operations in the terminal, let's look at another way to use Webpack.

Using Webpack with configuration files

Webpack has a lot of other advanced features (such as the loaders and plugins described later in this article), which can all be implemented in command-line mode, but, as already mentioned, it's not easy and error-prone, a better way is to define a configuration file, This configuration file is also a simple JavaScript module that can put all the information about the build in it.

Or continue with the example above to illustrate how to write this configuration file, create a new file named Webpack.config.js under the root of the current practice folder, and make the simplest configuration in it, as shown below, which contains the path of the portal file and the place where the packaged file is stored.

module.exports = {  entry:  __dirname + "/app/main.js",//已多次提及的唯一入口文件  output: { path: __dirname + "/public",//打包后的文件存放的地方 filename: "bundle.js"//打包后输出文件的文件名 }}

Note : "__dirname" is a global variable in node. js that points to the directory where the current execution script resides.

Now if you need to pack the files only need in the terminal you run the webpack(非全局安装需使用node_modules/.bin/webpack) command, this command will automatically refer to the configuration options in the Webpack.config.js file to package your project, the output is as follows


Webpack


Also learned a method of using Webpack, and do not have to worry about the annoying command line parameters, there is no feeling very cool. Have you ever thought that if you can even webpack(非全局安装需使用node_modules/.bin/webpack) use this command can not, that feeling will be more cool ~, continue to see below.

Perform packaging tasks more quickly

Executing a command similar to node_modules/.bin/webpack this is annoying and error-prone, but thankfully NPM can boot the task and configure it to npm start replace these cumbersome commands with simple commands. Set the settings for the NPM script section in Package.json, as follows.

{  "name": "webpack-sample-project",  "version": "1.0.0",  "description": "Sample webpack project", "scripts": { "start": "webpack" //配置的地方就是这里啦,相当于把npm的start命令指向webpack命令 }, "author": "zhang", "license": "ISC", "devDependencies": { "webpack": "^1.12.9" }}

Note:The script section in Package.json has already added a path by default before the command node_modules/.bin , so you do not need to write the detailed path that is indicated above, either globally or locally installed Webpack.

NPM start is a special script name, its particularity table now, the command line npm start can be used to execute the relevant command, if the corresponding script name is not, you start want to run on the command line, the npm run {script name} npm run build following is the execution npm start After the output of the command line is displayed


Npmstarttermialresult

Now just need to use to npm start package the file, there is no thought webpack also so, but do not underestimate Webpack, its powerful features are included in its series of configurable options, we see one item.

Webpack's powerful features generate source Maps (making debugging easier)

Development is always inseparable from debugging, if you can more convenient debugging of course, can improve the development efficiency, but after the packaging of the file sometimes you are not easy to find the wrong place corresponding source code location, source maps is to help us solve the problem.
With a simple configuration, Webpack can generate source maps for us when packaging, which gives us a way to compile files and source files, making the compiled code more readable and easier to debug.

Configuring the source maps in the Webpack configuration file requires configuration devtool , which has the following four different configuration options, each with its advantages and disadvantages, as described below:

Devtool Options Configuration Results
Source-map produce a complete and fully functional file in a separate file. This file has the best source map, but it slows down the build of the packaged files;
Cheap-module-source-map Generate a map with no column mappings in a separate file, with no column mappings to improve project build speed, but also make browser developer tools only correspond to specific lines, not corresponding to the specific columns (symbols), will cause inconvenience to debugging;
Eval-source-map Use the eval package source file module to generate a clean, complete source map in the same file. This option can generate a complete sourcemap without affecting the build speed, but the execution of the output JS file after packaging has a potential for performance and security. But in the development phase this is a very good option, but in the production phase must not use this option;
Cheap-module-eval-source-map This is the quickest way to generate a source map when packaging a file, the generated source map will be displayed with the packaged JavaScript file, no column mappings, and eval-source-map options have similar drawbacks;

As mentioned in the table above, the above options are packaged from top to bottom faster and faster, but at the same time there are more and more negative effects, and the result of a faster build speed is a certain impact on the execution of the packaged files.

In the learning phase and in small to neutral projects, eval-source-map is a good option, but remember to use it only in the development phase, continue the above example, the following configuration

module.exports = {  devtool: ‘eval-source-map‘,//配置生成Source Maps,选择合适的选项  entry:  __dirname + "/app/main.js", output: { path: __dirname + "/public", filename: "bundle.js" }}

cheap-module-eval-source-mapThe method builds faster, but is not conducive to commissioning, and is recommended for large projects considering the DA time cost is used.



This article refers to:
Links: http://www.jianshu.com/p/42e11515c10f
Source: Pinterest

 

 

Webpack Getting Started learning

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.