Detailed front-end modular tool-webpack

Source: Internet
Author: User
Tags base64

Webpack is a module bundler, put aside the profound problem of Chinese characters, we call him a "modular management tool." With JS can do more and more things, browser, server, JS seems to be everywhere, at this time, so that the increasing number of JS code becomes reasonable and orderly is particularly necessary, also came into being a lot of modular tools. From server-side to browser-side, from native non-modular systems ' <script> ' to Commonjs-based and AMD-compliant implementations to ES6 modules. For modularity and better modularity, we are always on the road to exploration.

But these methods of implementing modularity have their drawbacks more or less. For example, using the ' <script> ' tag to import JS module, the order is not good grasp and we need to sort out the possible conflicts and dependencies, using the COMMONJS specification to solve the problem, it makes our server-side modules are reused, but on the browser side, the network requests are asynchronous, Cannot require multiple module in parallel. ES6 modules is only a small part of the implementation, and want to get all the browser support, compared to still need a considerable period of time.

Of course, flexible module management is just one of the many features of Webpack, and it has many outstanding features:

1 - It supports both the COMMONJS and AMD specifications (even mixed forms);2 - It can be broken into a complete package, or it can be divided into multiple parts, asynchronously loaded at run time (can reduce the time of first load);  3 - dependencies are processed at compile time, which reduces the size of the run-time package, and4 -loaders allows the file to be preprocessed at compile time, which can help us do many things, such as pre-compiling the template, Base64 processing of images;5 -rich and extensible plug-ins can adapt to changing needs.
First, Webpack detailed

Recently in learning ES6 and react related knowledge, in order to more convenient to write their own code, to write a scaffold generator-reactpack. A basic Webpack.config.js file can be seen in the generated project:

1 varWebpack = require (' Webpack '));2Module.exports = {3 entry: [4' Webpack/hot/only-dev-server ',5'./js/app.js '6     ],7 output: {8Path: './build ',9FileName: ' Bundle.js 'Ten     }, One module: { A Loaders: [ -{test:/\.js?$/, loaders: [' React-hot ', ' Babel '], exclude:/node_modules/ }, -{test:/\.js$/, exclude:/node_modules/, Loader: ' Babel-loader '}, the{test:/\.css$/, Loader: "Style!css" }, -{test:/\.less/,loader: ' Style-loader!css-loader!less-loader '} -         ] -     }, + resolve:{ -Extensions:[', '. js ', '. JSON '] +     }, A plugins: [ at         NewWebpack. Noerrorsplugin () -     ] -};

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:

1 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:

1 entry: [2     ' Webpack/hot/only-dev-server ',3     './js/app.js '4  ]

When entry is an object, we can build different files into different files and use them on demand, such as on my Hello page as long as \<script src= ' build/profile.js ' ></script> The introduction of Hello.js can:

1 entry: {2     Hello: './js/hello.js ',3     form: './js/form.js '4 }

2.output

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

1 output: {2     path: './build ',3     filename: ' Bundle.js '4  }

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):

1 module: {2    loaders: [3         {test:/\.js?$/, loaders: [' React-hot ', ' Babel '], Exclude:/node_modules/ },4         {test:/\.js$/, exclude:/node_modules/, Loader: ' Babel-loader ' },5         {test:/\.css$/, Loader: "Style!css" },6         {test:/\.less/, Loader: ' Style-loader!css-loader!less-loader '}7    ]8 }

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:

1 {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:

1 require ('./bootstrap.css '); 2 require ('./myapp.less '); 3 var img = document.createelement (' img '); 4 img.src = 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 [Extract-text-webpack-plugin] plugin mentioned below.

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 ' Webpack/hot/only-dev-server ' in the entry parameter, so we can use react-hot-loader just by turning on the--hot parameter when we start the Webpack development server. This is defined in the Package.json file:

1 "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:

1 resolve:{2     extensions:[", '. js ', '. JSON ']3 }

Then we want to load a JS file, as long as require (' common ') can load the Common.js file.


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:

1 plugins: [2     New Webpack. Noerrorsplugin ()3 ]


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:

1 externals: {2     "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:

1 require ("./mods/" + name + ". 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. Analysis directory: './mods ';
2. Extract the regular expression: '/^.*\.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):

1 var currentbase = process.cwd (); 2 var context = AbcOptions.options.context?  3 path.isabsolute (entrydir)? EntryDir:path.join (Currentbase, Entrydir);

second, why Webpack?

Webpack and gulp are not contradictory, even use together will get the maximum benefit, webpack and gulp. Using Webpack for assets compiling, packaging with Gulp seems to be to get them to do their own work and use their strengths.

About the positioning of tools

Webpack's positioning is module bundler, which, as a modular tool, looks more like [browserify] than [Gulp], a flow-based automation build tool. However, the same is true.

The difference in function and mode of use

Webpack provides some very useful functions, such as those we have experienced earlier, such as image processing, resolve processing, building apart [webpack-code-splitting] and so on. Many other tools require plug-in functionality, Webpack as long as you configure it.

Sometimes a thing in the end, I have to toss it over perhaps the experience is even more profound.

Third, expand reading

-[Webpack]
-[Cake-webpack-config]
-[WEBPACK-HOWTO]
-[webpack-compared]

Detailed front-end modular tool-webpack

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.