Webpack User Guide

Source: Internet
Author: User
Tags naming convention unique id install node

Webpack is now the most popular modular management and packaging tool for front-end resources.

What is Webpack

Webpack is now the most popular modular management and packaging tool for front-end resources. It can package many loose modules according to dependencies and rules into front-end resources that meet the deployment of the production environment. You can also code-separate modules that are loaded on demand, and then load asynchronously when you actually need them. With loader conversion, any form of resources can be seen as modules, such as CommonJs modules, AMD modules, ES6 modules, CSS, images, JSON, coffeescript, less and so on.

Features of Webpack

What is the difference between Webpack and other modular tools?

    • Code splitting
      Webpack has two types of organizational modules that are dependent on the way, synchronous and asynchronous. Asynchronously relies as a split point to form a new block. After the dependency tree has been optimized, each asynchronous chunk is packaged as a file.
    • Loader
      The Webpack itself can only handle native JavaScript modules, but the loader converter can convert various types of resources into JavaScript modules. In this way, any resource can be a module that Webpack can handle.
    • Intelligent parsing
      Webpack has an intelligent parser that can handle almost any third-party library, regardless of whether they are in the form of CommonJS, AMD or ordinary JS files. Even when loading dependencies, the dynamic expression require ("./templates/" + name + ". Jade") is allowed.
    • Plug-in System
      Webpack also has a feature-rich plug-in system. Most of the content features are based on this plug-in system, and you can develop and use open source Webpack plug-ins to meet a wide range of requirements.
    • Fast Running
      Webpack uses asynchronous I/O and multi-level caching to improve operational efficiency, which allows Webpack to compile quickly and incrementally with incredible speed.
Getting Started with installation

To install node. js, node. js comes with the Package Manager Npm,webpack can be installed via NPM.

Install Webpack with NPM:

$ npm install webpack -g

At this point Webpack has been installed in the global environment, you can try the command line webpack-h.

Typically, we install Webpack into a project's dependencies so that we can use the Webpack of the project's local version.

# 进入项目目录# 确定已经有 package.json,没有就通过 npm init 创建# 安装 webpack 依赖$ npm install webpack --save-dev

View Webpack

# 查看 webpack 版本信息$ npm info webpack

Install the specified version of Webpack

$ npm install [email protected] --save-dev

If you need to use the Webpack development tool, install it separately:

$ npm install webpack-dev-server --save-dev
Use

First create a static page index.html and a JS entry file Entry.js:

<!-- index.html -->
// entry.jsdocument.write(‘It works.‘)

Then compile the entry.js and package to Bundle.js:

$ webpack entry.js bundle.js

The packaging process displays logs:

Hash: e964f90ec65eb2c29bb9Version: webpack 1.12.2Time: 54ms Asset Size Chunks Chunk Namesbundle.js 1.42 kB 0 [emitted] main [0] ./entry.js 27 bytes {0} [built]

Open index.html with your browser and you'll see It works. 。 Next add a module module.js and modify the ingress Entry.js:

// module.jsmodule.exports = ‘It works from module.js.‘
// entry.jsdocument.write(‘It works.‘)document.write(require(‘./module.js‘)) // 添加模块

Re-packaging Webpack entry.js bundle.js after refreshing the page to see the changes

It works.It works from module.js.Hash: 279c7601d5d08396e751Version: webpack 1.12.2Time: 63ms Asset Size Chunks Chunk Namesbundle.js 1.57 kB 0 [emitted] main [0] ./entry.js 66 bytes {0} [built] [1] ./module.js 43 bytes {0} [built]

Webpack parses the entry file and parses the individual files that contain the dependencies. These files (modules) are packaged in Bundle.js. Webpack assigns each module a unique ID and indexes and accesses the module through this ID. When the page starts, the code in Entry.js is executed first, and the other modules are executed when the require is run.

Loader

Webpack itself can only handle JavaScript modules, and if you want to work with other types of files, you need to convert using loader.

Loader can be understood as a converter for modules and resources, which itself is a function that accepts the source file as a parameter and returns the result of the transformation. This allows us to load any type of module or file, such as Coffeescript, JSX, less, or pictures, via require.

Let's take a look at the characteristics of loader.

    • Loader can be chained by pipeline, each Loader can convert the resource into any format and pass it to the next Loader, but the last Loader must return JavaScript.
    • Loader can be executed synchronously or asynchronously.
    • Loader is running in the node. JS environment, so you can do whatever it is possible.
    • Loader can accept parameters to pass configuration items to Loader.
    • Loader can be bound to different types of files through file extensions (or regular expressions).
    • Loader can be released and installed via NPM.
    • In addition to the main designation via Package.json, the usual modules can also be exported using a loader.
    • Loader can access the configuration.
    • Plugins allow loader to have more features.
    • Loader can issue additional arbitrary files.

Loader generally xxx-loader named in the way, XXX represents the loader to do the conversion function, such as json-loader .

Loader can be added when require () references a module, can be bound in a Webpack global configuration, and can also be used on a command line basis.

Next to the example of a section, we want to introduce a CSS file in the page style.css, home will style.css also as a module, and then use Css-loader to read it, and then use Style-loader to insert it into the page.

/* style.css */body { background: yellow; }

Modify Entry.js:

require("!style-loader!css-loader!./style.css") // 载入 style.cssdocument.write(‘It works.‘)document.write(require(‘./module.js‘))

Install loader:

npm install css-loader style-loader

Recompile the package, refresh the page, you can see the yellow page background.

If every time require CSS file to write loader prefix, is a very tedious thing. We can automatically bind the required loader based on the module type (extension).

Modify the Entry.js in to require("!style-loader!css-loader!./style.css") require("./style.css") , and then execute:

$ webpack entry.js bundle.js --module-bind ‘css=style!css‘
# 有些环境下可能需要使用双引号$ webpack entry.js bundle.js --module-bind "css=style!css"

Obviously, these two ways of using loader, the effect is the same.

Configuration file

Webpack can also be executed with the specified configuration file, in addition to passing parameters at the command line. By default, the Webpack.config.js file for the current directory is searched, which is a node. JS module that returns a JSON-formatted configuration information object or a configuration file with the--config option.

Example

Create a configuration file Webpack.config.js:

var webpack = require(‘webpack‘)module.exports = {  entry: ‘./entry.js‘,  output: {    path: __dirname,    filename: ‘bundle.js‘  },  module: {    loaders: [     {test: /\.css$/,loader: ‘style-loader!css-loader‘}]  }}
Webpack.config.js parameter explanation

The Webpack.config.js file is usually placed in the root of the project and is itself a standard COMMONJS specification module. There are several key parameters in the exported configuration object:

Entry

The entry parameter defines the packaged entry file, which is written in three ways, each of which is called a chunk:

type Example explain
String Entry: "./index/index.js" The configuration module is parsed into a module and loaded at startup.
The chunk name is main, and the specific package file name depends on the output configuration.
Array Entry: ['./src/mod1.js ', [...,] './src/index.js '] All modules are configured in the configuration order at startup
Loading, merging into the last module will be exported. Chunk name defaults to main
Object Entry:{index: ' ... ', login: [...]} Objectmultiple ingress package files are generated if passed in
keyis the chunk name, which value can be a string or an array.
{    entry: {        page1: "./page1",        //支持数组形式,将加载数组中的所有模块,但以最后一个模块作为输出        page2: ["./entry1", "./entry2"]    },    output: {        path: "dist/js/page",        publicPath: "/output/",        filename: "[name].bundle.js"    }}

The code will eventually generate a page1.bundle.js and page2.bundle.js, and store it in the./dist/js/page folder

Output

The output parameter is an object that defines the location and name of the exported file:

output: {        path: "dist/js/page",        publicPath: "/output/",        filename: "[name].bundle.js"    }
    • Path: Absolute path for packaging file storage
    • Publicpath: Access path when the Web site runs
    • FileName: The file name after packaging

When we define building multiple files in entry, filename can be changed to [Name].js used to define the names of different files after they are built.

Module

In Webpack Javascript,css,less,typescript,jsx,coffeescript, pictures and other static files are modules, the loading of different modules is through the module loader (Webpack-loader) to unified management. Loaders can be concatenated, the output of one loader can be used as input to the next loader, and eventually back to JavaScript: Loader use needs to be installed before adding to the configuration.

The loaders needs to be installed separately and needs to be configured under the Modules keyword under Webpack.config.js, loaders configuration options include the following:

    • Test: A regular expression that matches the extension name of the file processed by loaders (must)
    • Name of the Loader:loader (required)
    • Include/exclude: Manually add files (folders) that must be processed or block files (folders) that you do not need to process (optional);
    • Query: Provides additional setup options for loaders (optional)
Pretreatment of Loaders
    • Css-loader handling issues such as path references in CSS
    • Style-loader dynamically writing styles to CSS
    • Sass-loader Scss Compiler
    • Less-loader less compiler
    • Postcss-loader scss re-processing?
module: {        //加载器配置        loaders: [            //.css 文件使用 style-loader 和 css-loader 来处理            { test: /\.css$/, loader: ‘style-loader!css-loader‘ },            //.less 文件使用 less-loader、cssloader来编译            { test:/\.less$/, loader: ‘style!less‘}            //.scss 文件使用 style-loader、css-loader 和 sass-loader 来编译处理            { test: /\.scss$/, loader: ‘style!css!sass?sourceMap‘},        ]    }
React treatment of Loaders

Babel-loader Babel official website

// npm一次性安装多个依赖模块,模块之间用空格隔开npm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react
module: {  loaders: [    {    test:/\.jsx?$/,    exclude:/node_modules/,    loader:‘babel‘,    query:{presets:[‘react‘,‘es2015‘]}    }  ]}
ES6 Transformation Treatment of Loaders
    • Babel-loader and babel-preset-es2015
    • Install the above two plugins
       npm install babel-loader --save-dev npm install babel-preset-es2015 --save-dev
    • Create a configuration file for Bable
{  "presets": ["es2015"]}
Picture processing of Loaders
    • Url-loader
npm install --save-dev url-loadr
module: {  loaders: [    {      test: /\.(png|jpg|gif)$/,      loader: ‘url-loader?limit=10000&name=build/images/[name].[ext]‘    }  ]}

For the above configuration, if the picture resource is less than 10KB will be converted into base64 format dataurl, the other pictures will be stored in the Build/images folder.

Loaders's file processing
    • File-loader?
npm install --save-dev file-loader
module: {  loaders: [    {      test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,      loader: ‘file‘      },  ]}
Example
module: {        //加载器配置        loaders: [            //.css 文件使用 style-loader 和 css-loader 来处理            { test: /\.css$/, loader: ‘style-loader!css-loader‘ },            //.scss 文件使用 style-loader、css-loader 和 sass-loader 来编译处理            { test: /\.scss$/, loader: ‘style!css!sass?sourceMap‘},            //图片文件使用 url-loader 来处理,小于8kb的直接转为base64            { test: /\.(png|jpg)$/, loader: ‘url-loader?limit=8192‘}        ]    }
Plugins (Plugins)

Plug-ins (Plugins) are used to extend the functionality of Webpack, which take effect throughout the build process and perform related tasks.

Webpack has a lot of built-in plugins, and there are a lot of third-party plugins that allow us to do a richer function.

Ways to use plug-ins

To use a plugin, we need to install it via NPM, and then we have to add an instance of the plugin in the Plugins keyword section of the Webpack configuration (plugins is an array) to continue with the example, we have added a plugin that implements the copyright notice.

module.exports = {  plugins: [    new webpack.BannerPlugin("Copyright Nico inc.")    //在这个数组中new一个就可以了  ]}
Htmlwebpackplugin

The role of this plugin is based on a simple template to help you generate the final HTML5 file, which automatically refers to your packaged JS file. Each compilation inserts a different hash value in the file name.

Installation

npm install --save-dev html-webpack-plugin

This plugin automates some of the things we've done manually before, and we need to make some changes to the project structure that we've been working on since the formal use:

In the app directory, create an HTML file template, this template contains the title and other elements you need, during the compilation process, the plugin will generate the final HTML page according to this template, will automatically add the dependent CSS, Js,favicon and other files, In this example, we named the template file name index.tmpl.html, the template source code is as follows

Index.tmpl.html

<!DOCTYPE html>

Webpack.config.js

var webpack = require(‘webpack‘);var HtmlWebpackPlugin = require(‘html-webpack-plugin‘);module.exports = {plugins: [ new HtmlWebpackPlugin({ template: __dirname + "/app/index.tmpl.html"//new 一个这个插件的实例,并传入相关的参数 }) ]}
Extracttextplugin

Separating CSS and JS files

Installation

npm install --save-dev extract-text-webpack-plugin

Webpack.config.js

var webpack = require(‘webpack‘);var ExtractTextPlugin = require(‘extract-text-webpack-plugin‘);...  plugins: [    new HtmlWebpackPlugin({      template: __dirname + "/app/index.tmpl.html"    }),    new webpack.optimize.OccurenceOrderPlugin(),    new webpack.optimize.UglifyJsPlugin(),    new ExtractTextPlugin("style.css")  ]}
Merging common code

Project, for some common components, site common modules often need to be separated from other logic and then merged into the same file for long-time caching. To implement this feature, configure the reference:

var webpack = require(‘webpack‘);var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin; ···entry: {   a: ‘./index/a.js‘,   b: ‘./idnex/b.js‘,   c: ‘./index/c.js‘,   d: ‘./index/d.js‘},···plugins: [   new CommonsChunkPlugin(‘part.js‘, [‘a‘, ‘b‘]),   new CommonsChunkPlugin(‘common.js‘, [‘part1‘, ‘c‘])]···
Code compression

Webpack comes with a compression plug-in uglifyjsplugin that only needs to be introduced in the configuration file.

{  plugins: [    new webpack.optimize.UglifyJsPlugin({      compress: {        warnings: false      }    })  ]}

After adding this plugin, the speed of compilation is significantly slower, so it is generally only enabled in the production environment.

Other usage Caches

Cache everywhere, the best way to use the cache is to ensure that your file name and content are matched (the content changes, the name changes accordingly) Webpack can add a hash value to the packaged file name, using the following method, add a special string mixture ([name], [id] and [hash ]) before the output file name

var webpack = require(‘webpack‘);var HtmlWebpackPlugin = require(‘html-webpack-plugin‘);var ExtractTextPlugin = require(‘extract-text-webpack-plugin‘);module.exports = {  entry: __dirname + "/app/main.js",  output: {    path: __dirname + "/build",    filename: "[name]-[hash].js"  },  module: {},  plugins: [    new HtmlWebpackPlugin({      template: __dirname + "/app/index.tmpl.html"    }),    new webpack.optimize.OccurenceOrderPlugin(),    new webpack.optimize.UglifyJsPlugin(),    new ExtractTextPlugin("[name]-[hash].css")  ]}
Remove frequent dependencies from multiple files

When we often use external third-party libraries such as react, jquery, these libraries are often encountered in every business logic JS. If we need to have a jquery $ object in each file, we need to rely on jquery with require (' jquery ') at the head of each JS file that uses jquery. This is tedious and repetitive, so webpack provides us with a more efficient approach, where we can configure the variable names used in the configuration file, then Webpack will parse them automatically and help us with the introduction of these dependencies at compile time.

In Webpack.config.js

var webpack = require(‘webpack‘); ...plugins: [   new webpack.ProvidePlugin({       ‘Moment‘: ‘moment‘,       "$": "jquery",       "jQuery": "jquery",       "window.jQuery": "jquery",       "React": "react"   })]...
Set Environment commands

To tell Webpack what we want to be in the current environment, just write build_dev=1 webpck in the command so webpack through the configuration, it sets all the __dev__ variables we reference to TRUE.

We can pre-define the command in Package.json:

"scripts": {    "dev": "BUILD_DEV=1 webpack-dev-server --progress --colors",    "build": "BUILD_PRERELEASE=1 webpack -p"}

Then you can avoid entering lengthy commands:

Development time Input:

npm run dev

Enter at publish:

npm run build
Common commands

The use of Webpack is similar to Browserify, and here are a few common commands:

webpack 最基本的启动webpack命令webpack -w 提供watch方法,实时进行打包更新webpack -p 对打包后的文件进行压缩webpack -d 提供SourceMaps,方便调试webpack --colors 输出结果带彩色,比如:会用红色显示耗时较长的步骤webpack --profile 输出性能数据,可以看到每一步的耗时webpack --display-modules 默认情况下 node_modules 下的模块会被隐藏,加上这个参数可以显示这些被隐藏的模块
Directory structure
/ ├── shell/ 脚本 │ ├── conf/ 工程配置 │ ├── src/ 开发目录 │      ├── components/ 组件 │      ├── pages/ 页面 │      ├── ├── dist/ 自动生成 │ ├── test/ 测试 │ ├── node_modules/ 自动生成,包含.Node 依赖以及开发依赖 │ ├── static/ 库文件等,不会被webpack的loader处理,手动管理 │ └── etc

The Complete directory structure:

Projecttemplate/├──shell/node Script │├──│├──dev-server.js Local Development Server │├──build.js packaging script │├──utils.js Tool function │├──├──conf/Engineering configuration │├──│├──index.js Basic configuration file, where you can easily modify the Web Pack-related configuration │├──webpack.base.js webpack basic configuration, mainly loader, resolve configuration │├──webpack.dev.js webpack development configuration, mainly Eslint, Livereload, hot module replacement and related plug-in │├──webpack.prod.js webpack production configuration, mainly code compression confusion, image compression, plus HASH│├──KARMA.C Onf.js test Configuration │├──├──src/Development Directory │├──components/Component │├──pages/page (the project directory under the page needs to follow certain specifications to                Create the Webpack portal file, but these specifications can be adjusted; │├──index/home │├──images/Picture Resources │                ├──page.css style files, file names can be named according to their own │├──page.js script files and webpack portal files, file names can be configured in/conf/index.js │ ├──template.html template file and the HTML file to be composed, the file name can be configured in/conf/index.js │├──│├──dist        /auto-generated │  ├──test/Test (directories can be created, but the test file name must follow the *_test.js naming convention, which can be automatically generated in/conf/karma.conf.js modify configuration) │├──node_modules/ including node dependency and development dependent │├──static/library files, etc., will not be webpack loader processing, manual management │└──etc
Building a local server using Webpack

Want to let your browser monitor your code changes, and automatically refresh the modified results, in fact, Webpack provides an optional local development server, This local server is built based on node. JS and can implement the features you want, but it's a separate component that needs to be installed separately as a project dependency before being configured in Webpack

npm install --save-dev webpack-dev-server

Devserver as an item in the Webpack configuration option with the following configuration options

devserver configuration Options function Description
Contentbase The default Webpack-dev-server provides a local server for the root folder.
If you want to provide a local server for a file under another directory,
The directory where it should be set (this example is set to the "public" directory)
Port Set default listening port, if omitted, default to "8080"
Inline Set to True to automatically refresh the page when the source file changes
Colors Set to True to make the terminal output file a color
Historyapifallback Very useful when developing a single page application, it relies on the HTML5 history API,
If set to true, all jumps will point to index.html

The following configuration:

module.exports = {...devServer: {    contentBase: "./public",//本地服务器所加载的页面所在的目录    colors: true,//终端中输出结果为彩色    historyApiFallback: true,//不跳转    inline: true//实时刷新  }}






Webpack User 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.