Webpack Getting Started

Source: Internet
Author: User
Tags install node

Webpack Getting Started

Webpack is currently a popular packaging tool, how to install it?

1. Install Node Js

First, Webpack is a NodeJs-based tool, and you must first install NodeJs. NodeJs only needs to be installed once in your system.

2. Global Installation Webpack

We want to be able to use Webpack in any folder in the system, using the Webpack command, which requires us to install the Webpack globally. This can only be installed once, and each project will not need to be re-installed globally.

$ NPM Install Webpack-g

After a successful installation, you should be able to execute the webpack command in any directory, and if you do not have a configuration file for the project, you should see the current Webpack version and a help list for a command.

>WebpackWebpack 1.12.12usage:https://webpack.github.io/docs/cli.htmloptions:--help,-H,-? --config--context--entry--module-bind--module-bind-post--module-bind-pre--output-path--output-file--output -chunk-file--output-named-chunk-file--output-source-map-file--output-public-path--output-jsonp-function-- Output-pathinfo--output-library--output-library-target--records-input-path--records-output-path--records-path- -define--target--cache [DEFA Ult:true]--watch,-W--watch which closes when stdin ends--watch-aggregate-timeout--watch-poll--hot--debug-- Devtool--progress--resolve-alias--resolve-loader-alias--optimize-max-chunks--optimize-min-chunk-size--optimize -minimize--optimize-occurence-order--optimize-dedupe--prefetch--provide--labeled-modules--plugin--bail--PR ofile-d shortcut for--debug--devtool sourcemap--output-pathinfo-p shortcut for--optimize-minimize--json,-j   --colors,-c--sort-modules-by--sort-chunks-by--sort-assets-by--hide-modules--display-exclude--display-modules --display-chunks--display-error-details--display-origins--display-cached--display-cached-assets--display-reaso NS,--verbose,-voutput filename not configured.ps c:\study\webpack\w1>

Note that you are finally prompted that the Webpack configuration file is not currently found.

3. Install Webpack in the project

It is best to include a separate Webpack in your project so that you can manage your project more easily. Why is it a global installation, but also a partial installation? You can refer to the instructions here.

3.1 Confirming the creation of the NPM project file

First, you need to have created the NPM project file, and if not, use the init command to create it.

NPM Init

You need to answer a series of questions. Eventually you will get a NPM project file called Package.json, which is also good if you want to create it manually. You can even copy one directly over.

A newly created Package.json content should look like the following.

{  "name": "W1",  "version": "1.0.0",  "description": "",  "main": "Index.js",  "dependencies": {},  "Devdependencies": {},  "scripts": {    "test": "Echo \" Error:no test specified\ "&& exit 1"  },< c11/> "keywords": [],  "author": "",  "license": "ISC"}

3.2 Installing Webpack in a project

Now you can install Webpack in your project and use NPM's install command directly.

NPM Install Webpack--save-dev

--save-dev means that Webpack is a development tool that we need to save to the package. The Json file.

The install command can be simplified to a single character I, note is lowercase i.

--save-dev can also be simplified to uppercase S, written as-S, where you can see more detailed instructions for using instal.

NPM I webpack--s

You should see a long output, which is because Webpack is a very complex tool. It relies on a lot of other tools.

> NPM install webpack--save-dev[email protected] W1 '--[email protected] +--[email protected] +--[E Mail protected] +--[email protected] +--[email protected] | +--[email protected] | '--[email protected] +--[email protected] +--[email protected] | +--[email protected] | +--[email protected] | +--[email protected] | '--[email protected] +--[email protected] | +--[email protected] | | '---[email protected] |   '---[email protected] |   +--[email protected] |   +--[email protected] |   +--[email protected] |   +--[email protected] |   +--[email protected] | '--[email protected] +--[email protected] | '--[email protected] +--[email protected] | +--[email protected] | +--[email protected] | | '---[email protected] | +--[email protected] | | +--[email protected] | | '--[EMAIl protected] | +--[email protected] | | '---[email protected] | +--[email protected] | +--[email protected] | | +--[email protected] | | +--[email protected] | | '---[email protected] | +--[email protected] | +--[email protected] | +--[email protected] | | '---[email protected] | +--[email protected] | +--[email protected] | +--[email protected] | +--[email protected] | +--[email protected] | +--[email protected] | +--[email protected] | | '---[email protected] | +--[email protected] | |   '---[email protected] | | '---[email protected] | +--[email protected] | +--[email protected] | +--[email protected] | +--[email protected] | | +--[email protected] | | '---[email protected] | +--[email protected] | | '---[email protected] |   '---[email protected] | '--[Email protecTed] +--[email protected] | '--[email protected] +--[email protected] | '--[email protected] +--[email protected] +--[email protected] | +--[email protected] | +--[email protected] | +--[email protected] |   '---[email protected] |   +--[email protected] |   +--[email protected] | |   +--[email protected] | | |   +--[email protected] | | | |   +--[email protected] | | | |   '---[email protected] | | |   '---[email protected] | |   +--[email protected] | |   '---[email protected] |   +--[email protected] | '--[email protected] +--[email protected] | +--[email protected] |   '---[email protected] |   +--[email protected] | |   +--[email protected] | |   '---[email protected] |   |   +--[email protected] |   | |   '---[email protected] |   |   +--[email protected] |   | +--[EMAIL&NBSP;PROtected] |   | |   +--[email protected] |   | | |   '---[email protected] |   |   | |   +--[email protected] |   |   | |   +--[email protected] |   |   | |   '---[email protected] |   | |   +--[email protected] |   | |   '---[email protected] |   |   +--[email protected] |   | |   '---[email protected] |   |   +--[email protected] |   |   +--[email protected] |   |   +--[email protected] |   | |   '---[email protected] |   |   +--[email protected] |   |   +--[email protected] |   | |   +--[email protected] |   | | |   '---[email protected] |   | |   '---[email protected] |   |   +--[email protected] |   | |   +--[email protected] |   | |   '---[email protected] |   |   '---[email protected] |     |   +--[email protected] |     |   '---[email protected] |   +--[email protected] |   +--[email protected] | +--[Email protected] | |   '---[email protected] |   +--[email protected] | |   '---[email protected] |   +--[email protected] |     '---[email protected] |     +--[email protected] | |     '---[email protected] |   |     +--[email protected] |   |     '---[email protected] | '--[email protected] '--[email protected] +--[email protected] '--[email protected] '- -[email protected]npm WARN optional skipping failed optional dependency/chokidar/fsevents:npm WARN notsup not Compa  Tible with your operating system or architecture: [EMAIL&NBSP;PROTECTED]NPM WARN [email protected] No DESCRIPTIONNPM WARN [email protected] No repository field.>

At this point, you check the Package.json file again, it should be three more lines.

{  "name": "W1",  "version": "1.0.0",  "description": "",  "main": "Index.js",  "dependencies": {},  "Devdependencies": {    "webpack": "^1.13.2"  },  "scripts": {    "test": "Echo \" Error:no Test specified\ "&& exit 1"  },  "keywords": [],  "author": "",  "license": "ISC"}

4. Hello, Webpack

4.1 Packaging Plain script files

Write a common script, for example, a hellowrold script. Of course, this should be hello,webpack.

function Hello () {    alert ("Hello, webpack!");}

Save to the root of your project, the filename is called Hello.js

4.2 Creating a Webpack configuration file

The Webpack is packaged according to the configuration file configuration, and the default profile name is Webpack.config.js.

Webpack's job is simply to pack, you need to tell it what to pack, and where to export. The entry is the entrance, which is obviously output.

We have Webpack to package the Hello.js file and output it to the Bundle.js file.

Module.exports = {  //ingress  entry: './hello.js ',//  output filename    : {filename ' bundle.js '  }};

In the Command window, enter Webpack carriage return to execute. You should see the following output.

> Webpackhash:05c39d9076887c35f015version:webpack 1.13.2time:59ms    Asset     Size  Chunks             Chunk Namesbundle.js  1.44 KB       0  [emitted]  main   [0]./hello.js bytes {0} [built]>

The default portal file name is Index.js, and if you rename Hello.js to Index.js, you can also use the directory name directly without providing a file name.

Module.exports = {  //ingress, the default entry file name is Index.js  entry: ".",  //output file name outputs  : {    filename: ' bundle.js '  }};

The contents of the generated Bundle.js file are

/******/(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.E         Xports, __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_req  UIRE__.C = installedmodules;/******///__webpack_public_path__/******/__WEBPACK_REQUIRE__.P = "";/******/// Load entry module and return exports/******/return __webpack_require__ (0);/******/})/******************************        /([/* 0 *//***/function (module, exports) {function Hello () {    Alert ("Hello, webpack!"); }/***/ }/******/ ]);

The end is our script.

4.2 Embed a script in a Web page

Just a piece of script that needs to be placed in a Web page to execute. We can install a Webpack plugin that automatically helps us generate the hosting page Html-webpack-plugin to help us.

NPM Install Html-webpack-plugin--save-dev

You should see the following output.

> NPM install html-webpack-plugin--save-dev[email protected] W1 '--[email protected] +--[email  Protected] +--[email protected] | +--[email protected] | | +--[email protected] | | +--[email protected] | | +--[email protected] | | +--[email protected] | | +--[email protected] | | +--[email protected] | | +--[email protected] | | +--[email protected] | | +--[email protected] | | +--[email protected] | | +--[email protected] | | +--[email protected] | | +--[email protected] | | +--[email protected] | | +--[email protected] | | +--[email protected] | | +--[email protected] | | '---[email protected] | +--[email protected] | | +--[email protected] | | '---[email protected] | +--[email protected] | | '---[email protected] | +--[email protected] | +--[email protected] | | '--[EMAIL&NBSP;PROtected] | +--[email protected] |   '---[email protected] | '--[email protected] +--[email protected] +--[email protected] | +--[email protected] | | +--[email protected] | | | +--[email protected] | | | +--[email protected] | | | +--[email protected] | | | |   '---[email protected] | | | |   +--[email protected] | | | | '---[email protected] | | | '---[email protected] | | +--[email protected] | | | '---[email protected] | | +--[email protected] | | | +--[email protected] | | | +--[email protected] | | | +--[email protected] | | |   '---[email protected] | | | '---[email protected] | | +--[email protected] | | | '---[email protected] | | '---[email protected] | '--[email protected] '--[email protected]npm WARN optional skipping failed optional DEPENDENCY/CHOKIDAR/FSE VENTS:NPM WARN Notsup not compatible with Your operating system or architecture: [EMAIL&NBSP;PROTECTED]NPM WARN [email protected] No descriptionnpm WARN [Emai L protected] No repository field.>

This means the plug-in is ready to install.

Configure Webpack Use this plugin to help us generate a Web page and then automatically insert the packaged script into this page.

var htmlwebpackplugin = require (' Html-webpack-plugin '); module.exports = {  //ingress  Entry: ".",//  output filename  Output: {    filename: ' Bundle.js '  },  //Add our plugin will automatically generate an HTML file  plugins: [    new Htmlwebpackplugin ({      title: ' Hello Webpack '    }  ]};

In fact, this configuration file is a program, note the first line, be sure to add.

Re-executes the Webpack command. You will see that a webpage called index.html is generated more than once.

> Webpackhash:05c39d9076887c35f015version:webpack 1.13.2time:560ms     Asset       Size  Chunks             Chunk Names bundle.js    1.44 kB       0  [emitted]  mainindex.html  184  bytes          [ Emitted]   [0]./index.js bytes {0} [built]child html-webpack-plugin for "index.html":        + 3 hidden module S>

Open this page to check the inserted script reference.

<! DOCTYPE html><script type= "Text/javascript" src= "Bundle.js" ></script></body>

5. Summary

Webpack is a NodeJs-based packaging tool that we can use to help us package our scripts, and it can also help us generate host Web pages and automatically embed the packaged scripts into this web page.

Appendix:

Instructions for using the Html-webpack-plugin plugin

Webpack Getting Started

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.