Webpack Quick Start and combat

Source: Internet
Author: User
Tags install node

What is Webpack?

Webpack is a module wrapper. It will perform static analysis based on the dependencies of the modules, and then generate the corresponding static resources according to the specified rules.

This diagram basically explains what Webpack is for, and packages some interdependent modules (files) into one or more JS files, reducing the number of HTTP requests and improving performance. These interdependent modules can be pictures, fonts, coffee files, style files, less files, and so on.

1. Installation

Install first

Install node. js
node. JS contains a Package Manager: NPM

Basic commands

      webpack         // 最基本的启动webpack的方法      -w      // 提供watch方法;实时进行打包更新      -p      // 对打包后的文件进行压缩      -d      // 提供source map,方便调式代码

Global Installation

# npm install webpack -g

Project installation:

It is best to use Webpack in engineering to make Webpack a dependency on engineering. This allows you to choose a local version of Webpack, which does not force the use of global.

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

Using ES6

# npm install babel-loader --save-dev安装转码规则:       # npm install babel-preset-es2015 --save-devES7不同阶段语法提案的转码规则(共有4个阶段),选装一个# npm install --save-dev babel-preset-stage-0# npm install --save-dev babel-preset-stage-1# npm install --save-dev babel-preset-stage-2# npm install --save-dev babel-preset-stage-3参考格式:{    test: /\.js$/,    ‘babel?presets[]=es2015,presets[]=stage-0‘}

Compiling CSS

    安装css-loader:      # npm install css-loader  --save-dev    安装style-loader      # npm install style-loader  --save-dev    参考格式:    {        test: /\.css$/,        loaders: [‘style‘‘css‘‘autoprefixer‘]    }

Compile less

    npminstallless--save-dev    安装less-loader:     npminstallless-loader--save-dev    参考格式:    {        test: /\.less/,        loaders: [‘style‘, ‘css‘, ‘autoprefixer‘, ‘less‘],    }

Use Autoprefixer to automatically complement browser compatibility

    npminstallautoprefixer-loader--save-dev    参考格式:    {        test: /\.css$/,        loaders: [‘style‘, ‘css‘, ‘autoprefixer‘]    {        test: /\.less/,        loaders: [‘style‘, ‘css‘, ‘autoprefixer‘, ‘less‘],    }

Compiling files

    安装file-loader:     npminstallfile-loader--save-dev    参考格式:    {        test: /\.(eot|woff|svg|ttf|woff2|gif)(\?|$)/,        loader: ‘file-loader?name=[hash].[ext]‘    }

Compiling pictures

    npminstallurl-loader--save-dev    参考格式:    {    test: /\.(png|jpg)$/,    loader: ‘url?limit=1200&name=[hash].[ext]‘    }

Compiling JSX

    # npm install jsx-loader --save-dev    # npm install babel-preset-react --save-dev    参考格式:    {    test: /\.jsx$/,    loaders: [‘jsx‘‘babel?presets[]=es2015,presets[]=stage-0,presets[]=react‘]    }

Sample source Code

In the project directory, create a new webpack.config.js file, copy the following code, and then in a new app.js and Index.js file, write Console.log (' Hello World ');

Execute command: Webpack then find the build directory and see the compiled file.

    varWebpack =require(' Webpack '); Module.exports = {entry: {app:'./app ',//Compile the entry fileIndex'./index ',//Compile the entry file}, Output: {publicpath:'/build/',//Server root pathPath'./build ',//Compile to current directoryFileName' [name].js ' //The file name after compilation}, module: {loaders: [{test:/\.js$/, loader:' babel?presets=es2015 '}, {test:/\.css$/, loaders: [' style ',' CSS ',' Autoprefixer ']}, {test:/\.less/, loaders: [' style ',' CSS ',' Autoprefixer ',' less '],}, {test:/\. (eot|woff|svg|ttf|woff2|gif) (\?| $)/, loader:' File-loader?name=[hash]. [ext] '}, {test:/\. (png|jpg) $/, loader:' Url?limit=1200&name=[hash]. [ext] ' //Note the parameter of the limit below, when your image size is smaller than this limit, the Base64 encoded image is automatically enabled .}]}, plugins: [NewWebpack.optimize.CommonsChunkPlugin (' Common.js ')//The common module, packaged into the Common.js], resolve: {extensions: ["','. js ','. Jsx ']//Suffix name auto-complete}    };

Plugins: You can use a plug-in to tell a few public modules to load into the common.js, so you can better maintain the code, but note that:

3. Detailed 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:

1.entry

Entry can be a string or an array or an object.

When entry is a string, it is used to define the entry file:

     entry‘./js/main.js‘

When entry is a group, it also contains the portal JS file, another parameter can be used to configure the Webpack provided by a static resource server, Webpack-dev-server. Webpack-dev-server monitors changes to each file in the project, builds in real time, and automatically refreshes the page:

     entry: [         ‘webpack/hot/only-dev-server‘,         ‘./js/app.js‘     ]

When entry is an object, we can build different files into different files and use them on demand, for example, in my Hello page, as long as the introduction of Hello.js:

     entry{         hello: ‘./js/hello.js‘,         form: ‘./js/form.js‘     }

2.output

The output parameter is an object that defines the outputs of the built file. These include path and filename:

     output{         path: ‘./build‘,         filename: ‘bundle.js‘     }

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.

3.module

Regarding the loading of modules, we define them in module.loaders. This is done by matching the file names of the different suffixes with the regular expressions, and then defining different loaders for them. For example, define three loaders (!) in series for the less file. To define a cascade relationship):

Module:{  loaders: [{test:/\.js?$/, loaders: [' React-hot ', ' Babel '], exclude :/node_modules/  },{  test: /\.js$/, exclude:/node_modules/, Loader: ' babel-loader '   },{  test: /\.css$/, Loader: "style!css"   },{  test: /\.less/, loader: ' style-loader!css-loader!less-loader '   }     ] }

You can also add an loader that defines a picture resource such as PNG, JPG, which is automatically processed as a Base64 picture at less than 10k:

    { test: /\.(png|jpg)$/,loader: ‘url-loader?limit=10000‘}

After adding loader to the CSS and less and the pictures, we can not only require JS files like in node, we can also require CSS, less and even picture files:

require(‘./bootstrap.css‘require(‘./myapp.less‘vardocument.createElement(‘img‘require(‘./glyph.png‘);

However, it is necessary to know that such require files will be inline to the JS bundle. If we need to keep the require and want to take out the CSS file separately, you can use the plugin mentioned below [extract-text-webpack-plugin] .

In the first loaders configured in the example code above, we can see a loader called React-hot. My project is used to learn react write related code, so configure a react-hot loader, through which you can implement a hot replacement of the react component. We have configured it in the entry parameter, webpack/hot/only-dev- server so we can use React-hot-loader as long as the –hot parameter is turned on when we start the Webpack development server. This is defined in the Package.json file:

"scripts"2"start""webpack-dev-server --hot --progress --colors"3"build""webpack --progress --colors"4 }

4.resolve

Webpack when building a package, the file is searched by directory, and the extensions array in the Resolve property is used to configure which file suffixes the program can self-complement:

resolve:{     extensions:[‘‘,‘.js‘,‘.json‘] }

Then we want to load a JS file, as long as require(‘common‘) the Common.js file can be loaded.
5.plugin

Webpack provides [rich components] to meet different needs, and of course we can implement a component ourselves to meet our own needs. There is no special requirement in my project, so I just configure the Noerrorsplugin plug-in to skip the compile-time error code and record it, so that the package does not have an error after compiling the runtime:

plugins: [     new webpack.NoErrorsPlugin() ]

6.externals

This is necessary in practical development when we want to require some other class libraries or APIs in the project, and do not want the source code of these libraries to be built into the runtime files. At this point we can fix the problem by configuring the Externals parameter:

externals:"jquery""jQuery"3 }

This allows us to safely use these APIs in our projects:var jQuery = require("jquery");

7.context

When we require a module, if we include variables in the Require, like this:

require("./mods/"".js");

Then we can not know the specific module at the time of compiling. But this time, Webpack will do some analytical work for us too:

1.分析目录:‘./mods‘2.提取正则表达式:‘/^.*\.js$/‘;

So at this point in order to better match wenpack to compile, we can show it the path, as in the cake-webpack-config (we first ignore the role of Abcoption):

var currentBase = process.cwd();var context = abcOptions.options.context ? abcOptions.options.context : path.isAbsolute(entryDir) ? entryDir : path.join(currentBase, entryDir);

Reference: http://www.cnblogs.com/tugenhua0707/p/4793265.html

http://web.jobbole.com/tag/webpack/

http://www.3fwork.com/b401/003617MYM008091/

Webpack Quick Start and combat

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.