Webpack Getting Started

Source: Internet
Author: User
Tags compact script tag

Brief introduction

Webpack is a front-end build tool that provides a brief overview of its most common features and creates a webpack-based front-end development environment.

Sample Project

Contains two pages, List page list.html and detail page detail.html, only as Webpack packaged demos, not actually developing features. The sample project is a multi-page application, not a spa (single page app). We will use Webpack to compile and package the front-end resources.

Technology selection
    1. Style: Use SCSS, so you need to convert Scss to CSS.
    2. Script: Written in ES6, so you need to use Babel to convert ES6 code to ES5 (currently supported by the browser).
    3. UI Framework: React, so you need to convert JSX to JS code.
Basic use method to create a directory structure

Build an empty folder on the D disk, webpack-tutorial, as the root of the sample project. The structure is as follows:

    • Dist
      • Js
      • As1
    • Src
      • Jsx
      • Js
      • As1

The Dist directory holds the code generated by the Webpack package, which is also the. html page of the file that is referenced by the. SRC is our source code, usually cannot be referenced directly on the page, because the current browser does not fully support a lot of new technologies, such as ES6.

Installing Webpack

Suppose you have installed the Nodejs and NPM package management tools, and the version is at 3.8.0.

Open the command-line tool and navigate to D:\webpack-tutorial. First run NPM init to generate the Package.json file.

Then install Webpack, open the command line tool, execute:

NPM Install Webpack--save-dev

If the Webpack is installed globally, the runtime will error when the Extract-text-webpack-plugin plugin is installed later in this article, so it is recommended to install it locally.

Run Webpack

Now it's time to run Webpack, but now Webpack doesn't have any other capabilities, such as turning Scss into CSS.

Under the Src/js folder, build a common.js, the public script will be written in this file, which now only write a line of code:

Alert ("I ' m common");

Confirm that the current directory for the command line is: D:\webpack-tutorial, and then execute:

Webpack Src/js/common.js Dist/js/common.js

This will generate a Common.js file under the Dist/js folder. Next, create a list.html in the root directory, and then refer to dist/js/common.js through the script tag. Open list.html with a browser to see the page popup prompt box.

Open Dist/js/common.js, you can see that it and src/js/common.js are different, add the Webpack module mechanism, after the introduction of multiple modules, you will see in more detail to see its role:

/******/(function (modules) {//Webpackbootstrap/******///the module cache/******/var installedmodules = {};/****** ///the Require function/******/function __webpack_require__ (moduleid) {/******///Check If module is in cache/***** */if (Installedmodules[moduleid])/******/return installedmodules[moduleid].exports; /******///Create a new module (and put it into the cache)/******/var module = Installedmodules[moduleid] = {/******/ Exports: {},/******/Id:moduleid,/******/loaded:false/******/}; /******///Execute the module function/******/modules[moduleid].call (module.exports, module, Module.exports, __ WEBPACK_REQUIRE__); /******///Flag the module as loaded/******/module.loaded = true; /******///Return the exports of the module/******/return module.exports; /******/}/******///Expose the Modules object (__webpack_modules__)/******/__webpack_require__.m = modules; /******///Expose the module cache/******/__webpack_require__.c = InstalledmoduleS /******///__webpack_public_path__/******/__WEBPACK_REQUIRE__.P = ""; /******///Load entry module and return exports/******/return __webpack_require__ (0); /******/})/************************************************************************//******/([/* 0 *//***/ function (module, exports) {alert ("I ' m common");/***/}/******/]);

You can see that the above code is very not compact, and even contains a lot of comments. In a production environment, we want the code to be more compact, and you can use the following command:

Webpack Src/js/common.js Dist/js/common.min.js-p

This will generate a compact JS code:

!function (r) {function O (e) {if (T[e]) return T[e].exports;var N=t[e]={exports:{},id:e,loaded:!1};return R[e].call ( N.exports,n,n.exports,o), N.loaded=!0,n.exports}var t={};return o.m=r,o.c=t,o.p= "", O (0)} ([function (r,o) {alert ("I ' M common ")}]);

Building a module with COMMONJS

Modify Common.js:

var text = "I ' m common"; Module.exports = text;

Then add another file under Src/js list.js:

var text = require ("./common"); alert (text); Alert ("I ' m list");

As you can see, List.js relies on Common.js, and then runs Webpack again:

Webpack Src/js/list.js Dist/js/list.js

Modify list.html and now refer to Dist/js/list.js (previously Common.js). Open list.html, and you'll see it pop up the text box two times in turn. Now open list.js, and you'll see that it contains the code in Src/common.js and Src/list.js.

Add multiple Modules

Suppose this project requires jquery, open a command-line tool, install it:

NPM Install Jquery-save

This will generate a Node_modules folder in the Webpack-tutorial directory, and the modules installed through NPM will be in this folder. Modify the src/js/list.js so that it references jquery:

var $ = require ("jquery"); // ... No change in the middle $ ("body"). CSS ("Background-color", "#aaaaaa");

Using code splitting

Now create a new detail.html and create the detail.js under src/js/:

var $ = require ("jquery"); var text = require ("./common"); alert (text); Alert ("I ' m detail"); $ ("Body"). CSS ("Background-color", "#aaaaff");

It is almost the same as the list, just to demonstrate the situation of multiple files. Open the command line and run Webpack:

Webpack Src/js/detail.js Dist/js/detail.js

Open the Dist/js folder and you'll find that the detail.js and list.js files are the same size because they all contain common.js and jquery.js.

The volume of jquery.js is relatively large, so it is necessary to package jquery.js into a separate file, while List.js and Detail.js are packaged separately. In Webpack, you can use a technique called code splitting to implement.

Here jquery is a packaged file that needs no packaging and only references. But in real-world projects, there may be many third-party class libraries or frameworks that can be packaged together.

Rewrite list.js:

var text = require ("./common"); alert (text); Alert ("I ' m list"); Require.ensure ([], function () {var $ = require ("jquery"), $ ("body"). CSS ("Background-color", "#aaaaaa");}, "jquery");

Perform:

Webpack src/js/list.js dist/js/list.js--display-modules--display-chunks

Notice that the--display-modules and--display-chunks options are later used to display the modules that the file contains.

When the execution is complete, see:

hash:087ab301df8508cffa3e version:webpack 1.13.0 time:295ms Asset Size Chunks Chunk Names list.js 3.95 KB 0 [emitted] m Ain 1.list.js 267 KB 1 [emitted] jquery chunk {0} list.js (main) 308 bytes [rendered] [0]./src/js/list.js 248 bytes {0} [ Built] [1]./src/js/common.js bytes {0} [built] chunk {1} 1.list.js (jquery) 259 KB {0} [rendered] [2]./~/jquery/dist/ Jquery.js 259 KB {1} [built]

You can see that two files were generated: List.js and 1.list.js. Where list.js contains two files for List.js and Common.js, and 1.list.js contains jquery.js.

Note The above column: Chunk Names. The chunk name of 1.list.js is jquery, which is defined by the require.ensure third parameter of the method above. This name is used later when using the configuration file.

Then using the browser to open list.html, the debugger to view the page elements, you will find the head section of the newly inserted script tag, referring to the 1.list.js.

Use Chrome to view pages

Here, we find the first problem: the path of the reference is not correct .

Let's take a look at the second function of code splitting: load on demand. Modify the List.js:

var text = require ("./common"); alert (text); Alert ("I ' m list"); if (document.getElementById ("container")) {require.ensure ([], function () {var $ = require ("jquery"), $ ("body"). CSS (" Background-color "," #aaaaaa "); }, "jquery"); }

jquery is only loaded when the page has a container element. Because list.html is an empty page, it does not contain an element with an ID of container. Therefore, jquery is not loaded. Executing webpack again, opening list.html will find that the page is no longer inserted into the script tag.

Remove the If judgment from the list.js, then rewrite the detail.js in the same way as above, then execute Webpack on Detail.js. Then you'll soon find the second question:1.detail.js also contains jquery. In this case, the common part of multiple files is only split, not merged.

When using the config configuration file, it is a good solution to the above problem. In addition, the use of configuration files also saves a lot of input when running Webpack.

Using the config configuration file

Now, create a configuration file under the project root: Webpack.config.js.

var src = "./src/js/", dist = "./dist/js/"; Module.exports = {entry: {list:src + "list", Detail:src + "detail"}, output:{filename: "[name].js", Chunkfilename: "[n Ame].chunk[id].js ", Path:dist, Publicpath:dist}};

This configuration file is a purely JS file, so you can write some application logic in it. Notice the following configuration items:

    • Entry: Input, when an object, key is the name of the chunk, and the value is the module path.
    • Output.filename: The JS file name of the output.
    • Output.chunkfilename: The chunk file name of the output.
    • Path: The file path of the output.
    • Publicpath: The path that the page applies to (that is, the path to the previous bar error).

Once the configuration is complete, execute the command line:

D:\webpack-tutorial>webpack--display-modules--display-chunks hash:2ba5904a636a8ac64101 version:webpack 1.13.0 Time:856ms Asset Size Chunks Chunk Names detail.js 3.96 KB 0 [emitted] detail Jquery.chunk1.js 267 KB 1 [emitted] jquery List.js 4.01 KB 2 [emitted] list chunk {0} detail.js (detail) 267 bytes [rendered] [0]./src/js/detail.js 204 bytes {0} [b Uilt] [1]./src/js/common.js bytes {0} {2} [built] chunk {1} jquery.chunk1.js (jquery) 259 KB {0} {2} [rendered] [2]./ ~/jquery/dist/jquery.js 259 KB {1} [built] chunk {2} list.js (list) 311 bytes [rendered] [0]./src/js/list.js 248 bytes {2 } [built] [1]./src/js/common.js bytes {0} {2} [built]

You can see that three files were generated: Jquery.chunk1.js, which contains the Jquery.js (the [name] in the configuration file is the require.ensure third parameter in the method); Detail.js and List.js. Open list.html again below and find that both of the previous sections have been resolved.

Using Commonschunkplugin

In the example above, we used code splitting to generate the public jquery.js into the jquery.chunk1.js and to load it on demand (dynamically inserting the script tag into the page head).

If you want to package the public JS into the same JS file, and then manually add to the page, you can use the Commonschunkplugin plugin.

To modify the Webpack.config.js configuration file:

var webpack = require ("Webpack"); Module.exports = {plugins:[new Webpack.optimize.CommonsChunkPlugin ({name: ' lib ', Minchunks:2})]};

In order to make the article a little more compact, the same place in the configuration file is not listed again, the same.

Re-execute Webpack:

D:\webpack-tutorial>webpack--display-modules--display-chunks HASH:881D51E5A0D94BC015BC version:webpack 1.13.0 Time:858ms Asset Size Chunks Chunk Names detail.js 265 bytes 0 [emitted] detail list.js 262 bytes 1 [emitted] list lib.js 271 KB 2 [emitted] lib chunk {0} detail.js (detail) 155 bytes {2} [rendered] [0]./src/js/detail.js 155 bytes {0} [built] Chunk {1} list.js (list) bytes {2} [rendered] [0]./src/js/list.js bytes {1} [built] chunk {2} lib.js (Lib) 259 K B [Rendered] [1]./src/js/common.js bytes {2} [built] [2]./~/jquery/dist/jquery.js 259 KB {2} [built]

You can see that three files have been generated, detail.js, List.js, and Lib.js, where Lib.js contains Common.js and jquery.js.

At this point, remember to modify list.html and detail.html to manually introduce the Lib.js:

<script src= "Dist/js/lib.js" ></script> <script src= "Dist/js/list.js" ></script>

If we want to package only jquery and other third-party libraries into Lib (not including common.js), you can configure webpack.config.js:

var webpack = require ("Webpack"); Module.exports = {entry: {lib: ["jquery"],//Other libraries, can contain multiple LIST:SRC + "list", Detail:src + "detail"}, plugins:[new we Bpack.optimize.CommonsChunkPlugin ({name: ' lib ', Minchunks:infinity})]};

The results of the operation are as follows:

D:\webpack-tutorial>webpack--display-modules--display-chunks hash:c0a9b7c514a8a8ad5585 version:webpack 1.13.0 Time:839ms Asset Size Chunks Chunk Names detail.js 385 bytes 0 [emitted] detail lib.js 271 KB 1 [emitted] Lib List.js 382 Bytes 2 [emitted] list chunk {0} detail.js (detail) 218 bytes {1} [rendered] [0]./src/js/detail.js 155 bytes {0} [built] [1]./src/js/common.js bytes {0} {2} [built] chunk {1} lib.js (lib) 259 KB [rendered] [0] multi lib bytes {1} [Buil T] [2]./~/jquery/dist/jquery.js 259 KB {1} [built] chunk {2} list.js (list) 215 bytes {1} [rendered] [0]./src/js/list.js bytes {2} [built] [1]./src/js/common.js bytes {0} {2} [built]

You can see that Common.js is included in both List.js and Detail.js, and Lib.js contains a third-party jquery.js. The advantage of this is that the third-party library can be packaged as a CDN without being affected by the common.js that can be frequently changed.

Use Webpack loader to handle multiple resources

Webpack loader is somewhat similar to a pipe used to enhance Webpack's ability. If we need to parse the SCSS code, we need to scss-loader, after this pipeline scss converted to CSS, if you need to parse ES6 code, you need Babel-loader, after this pipeline ES6 converted to ES5. Wait, and so on.

Introduce styles

Let's look at the first loader:css loader. It is used to introduce style sheets into the current file.

Let's start with a little bit of prep work:

    • Create a list.css file under the src/css/folder with one line of code: Body{background: #aaa;}
    • Because now no longer demonstrates the processing of multiple files, so in webpack.config.js to delete detail:src + "detail" this line.
    • Delete all the code in Src/js/list.js

Install Css-loader:

NPM Install Css-loader--save-dev

Modify List.js

Require ("CSS!.. /css/list.css ");

Run the Webpack again and you can see that Dist/js/list.js will list.css included:

D:\webpack-tutorial>webpack--display-modules--display-chunks hash:a669b2f88986bbfd0da0 version:webpack 1.13.0 time:585ms Asset Size Chunks Chunk Names list.js 3.29 KB 0 [emitted] list Chunk {0} list.js (list) 1.73 KB [rendered] [0] ./src/js/list.js bytes {0} [built] [1]./~/css-loader!. /src/css/list.css 186 bytes {0} [built] [2]./~/css-loader/lib/css-base.js 1.51 KB {0} [built]

At this point, if you open list.html, you will find that there are no changes, this is because the role of css-loader is simply to link the CSS file into the script, but do not do any processing.

At this point, if you want to render the contents of the style to the page, you need to install another loader:style-loader.

Clearly, the principle of design is: A loader only do one thing.

NPM Install Style-loader--save-dev

Then modify the List.js

Require ("Style!css!.. /css/list.css ");

This is a chained syntax that means: first load the List.css file with Css-loader and then render it with Style-loader.

Run Webpack again, then open list.html and discover that the page has been loaded with the LIST.CSS style and the page background becomes gray (#aaa).

Using Chrome to view the source of the page, you will find that the style is embedded in the list.js instead of being introduced to the page via the link tag. This poses a problem: the page flashes . When you frequently refresh the page, you will find that the page is the default white until the script is loaded and the script is not grayed out until it has finished loading.

For a Web component, it should contain HTML constructs, CSS stylesheets, JS scripts that control behavior, and may contain fonts and pictures. Collectively referred to as resource assets, they can all be packaged into a JS file via Webpack. If you are developing a Web component, doing so is usually not a big problem, because the Web component is just a small area of the page. However, if it is a global style, the flicker problem before the resource is loaded can affect the user experience.
The picture and HTML are packaged in JS, and the corresponding loader is required, and this is not a demo.

As a result, we want to build the CSS file into the Dist/css folder, and then use the link tag to refer to it in the traditional way instead of generating it into the list.js script. Now, re-edit the Webpack.config.js:

var src = "./src/js/", dist = "./dist/js/"; Module.exports = {entry: {list:src + "list"}, output:{filename: "[name].js", Chunkfilename: "[name].chunk[id].js", Path : Dist, publicpath:dist}, module:{loaders:[{test:/\.css$/, loaders:["style", "CSS"]}]}};

The configuration of the loaders is added here. Then modify the List.js:

Require (".. /css/list.css ");

Then run the Webpack again, you will find no change, LIST.CSS is still packaged into the list.js. Modify the configuration above, but put the usage rules of loader into the configuration, and no other changes.

In order to package the CSS into the Dist/css folder, another Webpack plugin is required: Extract-text-webpack-plugin. Open the command line to install:

NPM Install Extract-text-webpack-plugin--save-dev

Then modify the webpack.config.js configuration file:

var src = "./src/js/", dist = "./dist/js/"; var extracttextplugin = require ("Extract-text-webpack-plugin"); Module.exports = {entry: {list:src + "list"}, output:{filename: "[name].js", Chunkfilename: "[name].chunk[id].js", Path : Dist, publicpath:dist}, module:{loaders:[{test:/\.css$/, Loader:ExtractTextPlugin.extract ("style", "CSS")}]}, p lugins:[New Extracttextplugin (".. /css/[name].css ", {allchunks:true})]};

Run Webpack again, and you can see that the List.css file is generated under the Dist folder. Note the parameters of the new extracttextplugin in plugins, the first parameter specifies the location of the generated CSS file, which is relative to the Output.path (./dist/js/) in the configuration, rather than the project's root directory (d:\ webpack-tutorial).

Modify the list.html and refer to the CSS file you just generated in the head to see everything is OK:

<link href= "Dist/css/list.css" rel= "stylesheet"/>

Doing so much work on it is equivalent to copying a copy of list.css from the Src/css folder to the Dist/css folder, which doesn't seem to make much sense. Under normal circumstances, the Scss file is written under Src/css and then generated into DIST/CSS. As you may have guessed, we need to install a loader again: Sass-loader.

NPM Install Sass-loader Node-sass--save-dev

Then modify the configuration file again:

module:{loaders:[{test:/\.css$/, Loader:ExtractTextPlugin.extract ("style", "CSS")}, {test:/\.scss$/, Loader:extrac Ttextplugin.extract ("Style", "Css!sass")}]}

Add a sass-loader to handle the. scss file. Then delete src/css/list.css, and then create the List.scss file:

$BG-main: #aaa; body{background: $BG-main;}

Modify the List.js require("../css/list.scss"); . Then run Webpack again, and after success you can see the CSS generated under DIST/CSS. As a result, you can write scss files in your project.

Using Babel to process ES6

ES6 (ES2015) was introduced in 2015, but the browser support is limited now. But fortunately there are babel such artifacts, you can convert ES6 to the browser now support ES5. With the above experience, the back is much easier, because it is very similar.

Install Babel-loader and babel-preset-2015 first:

NPM Install Babel-loader babel-core babel-preset-es2015--save-dev

Many people may ask: what does babel-preset-es2015 do? Simply put, is Babel itself is nothing to do, to rely on preset to complete, the purpose is also for the structure of more concise it.

Modify Webpack.config.js, add Babel-loader:

module:{loaders:[{test:/\.jsx?$/, exclude:/node_modules/, Loader: ' Babel ', query: {presets: [' es2015 ']}}]}

Now, modify list.js and write a ES6 code:

var arr = [1,2,3].map (x=> x+1); Alert (arr);

Run Webpack, and then open dist/js/list.js, and you will see that the lambda expression x=>x+1 has been converted to an anonymous function:

function (module, exports) {"Use strict"; var arr = [1, 2, 3].map (function (x) {return x + 1;}); alert (arr);}

Introduction of React

Because we use react as the front-end UI framework, we need to let WEBAPCK support it. The difference is that react is a preset for Babel, not a loader of webpack. Now install it first:

NPM Install react react-dom babel-preset-react--save-dev

Here react and react-dom are the core modules of react; Babel-preset-react is babel for preset.

Then modify the Webpack.config.js:

{test:/\.jsx?$/, Loader: ' Babel-loader ', exclude:/node_modules/, query:{presets: [' es2015 ', ' React ']}}

Create a HELLO.JSX under the Src/jsx folder to test the react:

var React = require ("React"); var reactdom = require ("React-dom"); var hellomessage = React.createclass ({render:function () {return <div>hello {this.props.name}</div>;}}); Reactdom.render (

Modify Src/js/list.js:

Import Hello from ". /jsx/hello.jsx ";

Here can not require, only import.

To modify list.html, add a line of code to the body: <div id="container"></div> . Open the list.html and you'll see the word "Hello Zhang Ziyang".

The generated dist/js/list.js will become very large, because it contains a lot of react code, you can use the aforementioned features to generate multiple files, which is no longer demonstrated here.

Summarize

This article can only be counted as a process guide, not a detailed explanation. First of all, the most common functions, advanced functions need to be studied again. Now briefly recap: we first configured the Webpack environment by running Webpack using the command line, and then we learned the code splitting, used the configuration file, and extracted the common code. Finally, support for Sass, ES6, and react is completed by installing and configuring loader. Let's begin to code happily!

Thanks for reading, I hope this article can bring you help!

Webpack Getting Started

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.