Webpack Getting Started

Source: Internet
Author: User

First, Modular:

1, what is modular?

is to consider a file as a module, the module does not affect each other, mainly for the JS file.

2. Why does the idea of modularity occur?

The original JS files are in the HTML through the <script stc= ' xxx.js ' > to introduce, when the JS file a lot of problems will arise:

(1), the pollution conflict between variables.

(2), because the browser is introduced into the JS file in the order of loading, but also in some JS files using other JS file methods, variables or calls to introduce plug-in methods, and so on, which require us to manually adjust the loading order.

(3), the time is too long, the code maintenance management difficulties.

(4), the introduction of such a code structure is not clear, redundant

So we have a modular idea, we set up a starter file entry.js, export the module interface through module.exports and exports, import the module through the Require (), and then rely on each module to call each other,

In the end we only need to introduce a entry.js file in the HTML file.

3, the principle of modular implementation:

There are three free variables in each module require, module, exports, where module and exports are responsible for exporting the interface, require is responsible for importing other modules.

To achieve the independence of each module, we will use each file code to execute the function package immediately, passing three free variables as parameters.

Module.export is an object that stores the interface to be exported by the module, and exports a reference to Module.exports, we assign a value to the Module.exports object or add a property, and finally return the export interface via return.

Other modules through the Require (' Filenamepath ') method introduced to get the module interface, the basic principle is to read the module file code and then execute, get the execution of the return value is the module interface, in order to avoid each execution, generally set the caching mechanism.

4. Modular specification (COMMOMJS, Amd/cmd)

These are some of the standard APIs for modular development.

Note: JS file can be loaded asynchronously, but all JS file execution must be synchronous, that is, serial, which is due to the characteristics of JS single-threaded decision.

(1), CommonJs

COMMONJS is mainly defined as a server-side API, the module is the Reqire synchronization module (after the load executes a module before continuing to the next), and then through the moduel.exports or exports export the module interface.

Browser clients require efficient speed, which is generally asynchronous loading of resources, so COMMONJS does not apply to clients.

The main realization of COMMONJS is Nodejs.

(2), Amd/cmd

AMD and CMD are also modular specifications, and unlike Commonjs, they are asynchronous loading modules that, when loading a module, can also load other modules in parallel and execute them.

But there are some differences between AMD and CMD:

AMD is preloaded, while loading the JS file module, also parse the execution of the modulo, (because it is to execute, so before loading a module, all of the module's dependent modules are loaded, to prepare for the module execution)

CMD is lazy loading (loading on demand), asynchronously loading the module, but does not execute and executes only when needed.

Advantages and Disadvantages

AMD is load efficient because it executes on one side of the load, but the load order is not necessarily uncontrolled.

The cmd loading sequence is controllable, but because the module is not executed in advance and JS is executed serially, it takes a long time.

Second, Webpack Introduction:

Webpack is a Module packager, Webpack start the entire project structure from the portal file, find the JavaScript module and some browsers do not directly identify the running, according to the specified rules to package it into the appropriate format to the export file.

Webpack is a more advantageous tool in the functionality of other module packaging management tools.

Iii. Advantages of Webpack

(1), Webpack provides us with a COMMONJS-based modular development environment that can be developed directly using the COMMONJS specification, and Webpack will be packaged as a browser-aware file.

(2), Webpack itself can only deal with JavaScript modules, but we convert various types of resources through the loader converter to the JavaScript module processing, so that any type of module webpack can be processed,

We can also use the new JavaScript language features that the browser does not recognize.

(3), Webpack can detect the change of JS file, automatically packaged as an export file in the appropriate format.

(4), Webpack has an intelligent parser, can handle almost any third-party library.

(5), rich plug-in system to meet a variety of needs.

Iv. Use of Webpack:

We will install Nodejs before use, we use NODEJS with NPM for package management.

1. Installation:

(1), execute the command global installation Webpack

Install webpack-g

(2), create a project folder, execute commands under the file, all the way to enter, generate Package.json, package management

NPM Init

(3), in the project directory to execute the command local installation:

Install Webpack--save-dev

(4), executes the command installs the development tool, executes the webpack-dev-server, will automatically create a local server, we enter the localhost:8080/html file name in the browser (the default is index.html) can access

Install webpack-dev-server--save-dev

2. Simple usage:

Create the index.html file and the Entry.js file in the project folder, and then use <script src> in the index.html file to introduce bundle.js

We execute webpack entry.js bundle.js under the project directory of the command line, and if there is no error, access the index.html file to see the result of code execution in index.js (this test code is arbitrary)

Syntax is: Wepack import file path exit file path [--module-bind ' loaded loader ']

The following loader is used to deal with non-JS file module and the browser does not recognize the new JS feature module, before using the NPM install download, such as Css-loader parsing CSS module loader

Install Css-loader--save-dev

3. Configuration file:

We write the portal file path, export file path, loaded loader, loaded plug-ins and so on to the configuration file, and then omit the command line Long command, the direct execution of Webpack can be packaged.

//Introducing Path module processing PathsvarPath = require (' path ');//introduce the Webpack module and import the Global Mount pluginvarWebpack = require (' Webpack '));//introduce the Commonschunkplugin global Mount plugin, extract the common code into the Common.js file, and then we need to introduce it manually in the HTML file ,//solve multiple modules to introduce the same module, so that the redundancy of the module is too high, so the extraction of public code, directly into the HTML filevarCommonschunkplugin = Webpack.optimize.CommonsChunkPlugin (' Common.js ')) Module.exports= {    //Getting Started file configuration, Path.join () path stitching, __dirname current pathEntry:path.join (__dirname, ' src/js/entry.js ')),    //Export File Configurationoutput: {//Exit PathPath:path.join (__dirname, ' bundle '),        //Public DirectoryPublicpath: './bundle ',        //Export File nameFileName: ' Bundle.js '}, Resolve: {//Specify the file name suffix that can be import, and import the suffix of these files can be omittedExtensions: ['. js ', '. Jsx ']    },    //Module Configurationmodule: {//introduced loader configuration array, loader need npm install download before useLoaders: [//files that match the. js suffix are processed using the Babel-loader preprocessing loader{test:/\.js$/, Loader: ' Babel-loader '},            //match the. css suffix file, using Style-loader and Css-loader processing{test:/\.css$/, Loader: ' Style-loader!css-loader '},            //match jpg and PNG images, use url-loader processing, and then pass the parameters to Url-loader, limit=8192 refers to the picture is less than 8KB, convert the picture to Base64 format{test:/\. (jpg|png) $/, loader: ' url-loader?limit=8192 '}, {test:/\.less$/, loader: ' Style-loader!css-loader!less-loader '}]}, plugins: [NewCommonschunkplugin ()]}

4. Development and Commissioning:

(1) Some command techniques:

General Webpack Disposable packaging does not meet our requirements.

We can use Webpack-w to turn on the listening mode, the module is not changed to cache in memory, the changed module is recompiled.

Of course we can also use webpack-dev-server , will start an express HTTP static server in localhost:8080, and in listening mode automatically run Webpack, automatically refresh the page, The server default current directory is the project directory, we enter the correct path to access the HTML file.

If the project is too large and the compilation time is longer, we use --grogress--colors to make the output with progress and color, as follows:

Webpack-w --progress--colors
Webpack-dev-server--progress--colors

(2), use NPM Test command:

We can adjust the scripts option in Package.json, as follows:

---------------------------------------

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.