Approaching webpack (3)-image processing,

Source: Internet
Author: User

Approaching webpack (3)-image processing,

In the previous chapter, we learned how to use webpack to pack css and compress js. This article describes how to use webpack to process images. Let's get started.

First, place a picture you like in the src/images directory, and set the image as a background image. The code is like this.

Src/index.html:

<div id="title"></div><div id="name"></div><div id="img"></div><script src="./entry1.js"></script><script src="./entry2.js"></script>

Src/css/index.css:

body{   background:red; }#title{  background:orange;    color:blue;      }#img{    background: url(../images/dog.jpg);    width: 500px;    height: 500px;}

OK. after we have finished writing the code, the webpack cannot be parsed. You can try it in a package and find an error. Well, an error will be reported if loader is not added!

Next, we will install the loader required for image packaging:

npm install --save-dev file-loader url-loader

While waiting for installation, let's first explain what the two loaders are doing:

File-loader: solves the problem of reference paths. We all know that webpack will eventually package each module into a file by introducing the background style to the background image with a url, therefore, the url path in the style is relative to the html page, rather than the path relative to the original css file. This will cause image import failure. This problem is solved using file-loader,File-loader can parse the url introduction in the project (not limited to css), copy the image to the corresponding path according to our configuration, and then according to our configuration, modify the file reference path after packaging to point to the correct File.

Url-loader:If there are many images, many http requests will be sent, which will reduce the page performance. This problem can be solved through url-loader.. Url-loader generates the dataURl by encoding the imported image. It is equivalent to translating image data into a string of characters. Then Package the string into a file, and you can access the image by introducing the file. Of course, if the image size is large, encoding will consume performance. Therefore, url-loader provides a limit parameter. files smaller than the limit byte will be converted to DataURl, and files larger than the limit will also be copied using file-loader. In fact, the function of url-loader is to determine whether the image needs to be converted to string Encoding Based on the configuration to make the project performance and speed faster.

Then, we will configure loader in the module. Now our module looks like this, and the limit parameter is used to determine the size range of the image to be converted to string encoding, the Unit is B.

module:{        rules: [            {              test: /\.css$/,              use: [ 'style-loader', 'css-loader' ]            },{               test:/\.(png|jpg|gif)/ ,               use:[{                   loader:'url-loader',                   options:{                       limit:500000                   }               }]            }          ]    },

Alas? No, you have installed two loaders. Why do you only use url-loader ?! Because url-loader has built-in file-loader. Here, file-loader is installed to make it easier for you to use it later.

OK. Let's package it and see what will happen. Open the page and you will find that the imported image is displayed.

Next, let's talk about how to separate css from js. The above css is imported to js through import and then packaged. This is not conducive to maintenance and violates js and css, the basic principle of html mutual separation. However, once css is separated, the original image path may be faulty. We will solve the problem below. However, webpack officially believes that css should be packaged into js to reduce http requests. Therefore, the benevolent sees the wise and sees the wise. How can we choose the specific situation.

In fact, it is very easy to solve this problem, using plug-ins,Extract-Text-Webpack-Plugin. I won't talk about how to install it. I have already said it many times. I just changed my name like the above installation method.

Since it is a plug-in, we need to introduce it in config and create an instance before using it:

Module: {rules: [{test:/\. css $ /,/* Modified the usage method */use: extractTextPlugin. extract ({fallback: "style-loader", use: "css-loader"})}, {Test :/\. (png | jpg | gif)/, use: [{loader: 'url-loader ', options: {limit: 500000}]}, // plug-in, plugins: [new uglify (), new htmlPlugin ({minify: {removeAttributeQuotes: true}, hash: true, template :'. /src/index.html '}),/* A new plug-in instance */   New extractTextPlugin ("css/index.css")],

OK. We packed the package with great enthusiasm. The error was reported mainly because extract-text-webpack-plugin does not currently support webpack4.x. What should we do? Don't worry. Let's find a solution:

Npm install -- save-dev extract-text-webpack-plugin @ next/* update version */

In this case, you can package it, but after completing the package, we find that index.html does not introduce the corresponding css, and there is no css on the page. Don't worry, let's proceed to the next step to solve this problem.

We define a PATH variable in config:

Var webpath = {publicPath: "http: // 192.168.199.124: 9090/"}/* is the host and port defined in devServer */

Then define a publicPath attribute in the output property:

output:{    path:path.resolve(__dirname,'dist'),    filename:'[name].js',    publicPath:webpath.publicPath},

In addition, you need to change the previously configured host in devServer to your own local host. My host is http: // 192.168.199.124. If you do not know it, you can use ipconfig in cmd to query it.

Then we run the npm server and found that the opened page already has images and styles.

Then we learned how to deal with the image problem in css. Next we will learn how to deal with the image in html (also using plug-ins and various plug-ins, you can go to github to find a plug-in that you like to handle the problem type ):

Here we use html-withimg-loader, and then configure the following in config:

Npm install html-withimg-loader -- save/* because it is also required in the production process, use the -- save command */
{    test: /\.(htm|html)$/i,     use:[ 'html-withimg-loader'] }

It's done ...... Simple.

The content in front of the package is not in the images folder. To put it in the images folder, you only need to configure our url-loader option. As mentioned above, we need to limit the limit size. Otherwise, the image will be transcoded within the range smaller than the limit. Let's just modify the code:

{   test:/\.(png|jpg|gif)/ ,   use:[{       loader:'url-loader',       options:{           limit:500,           outputPath:'images/'       }   }]}

We add an image to src/index.html:

<Div id = "title"> </div> <div id = "name"> </div> <div id = "img"> </div> <! -- Introduce images through src --> 

Write the following css under src/css/index.css:

Body {background: red ;}# title {background: orange; color: blue ;}# img {background: url (.. /images/dog.jpg); width: 500px; height: 500px;}/* set the image size */# htmlImg {width: 500px; height: 500px ;}

Then let's take a look at the results of npm run server. I would like to explain why npm run build was used in packaging and npm run server was used here?

  Generally, we have two environments: dev and prod, that is, the development environment and production environment. Generally, In the development environment, we use webpack-dev-server to create a node server through express, instead of packaging it. The webpack we learned earlier contains the requirements in the development environment, there is also content in the production environment. When we want to package and launch the entire project, we will compress js, compress images, and integrate resources to reduce http requests, however, in the development environment, we often need more functions to make the code easier to read and debug. Then, when we introduce images, we use an absolute address, that is, your local IP address after the node starts the server. If you do not use the npm run server to start the local server, images cannot be found.If you are interested, you can try npm run build and manually open the html under dist to see the effect.

Now, the image processing method is complete. In the next chapter, let's take a look at how to deal with less css precompiled languages such as sass. After all, css is rarely used to write styles.

 

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.