Webpack 4.0 breaking down (3) — assets

Time:2021-1-19

1、 Basic processing requirements of assets resources

Assets, refers to the resources that are referenced in a project. They are usually pictures and font files of various formats. Of course, they may also contain files with various other extensions(.json,.xmlCommon image and text resource processing includes:

  • Volume compression
  • Sprite chart merging and citation correction
  • Automatic reference path replacement of resources

2、 Webpack processing reference resources

2.1 resource packaging

webpackadoptfile-loaderProcess the resource file, which willrulesThe resource file hit by the rule is output to the specified directory according to the configured information (path, name, etc.), and its resource location address (output path) is returned, which is used for the production environmentpublicPathThe default output name is calculated based on the content of the original fileMD5 HashNamed.

staywebpack.config.jsAdd processing rules for image files in:

 {
    test:/\.(jpg|png|svg|gif)/,
    use:[{
      loader:'file-loader',
      options:{
        outputPath:'imgs/'
      }
    }]
  }

Execute the packing command to seepngThe name of the image resource is replaced withhashAnd output to the build folder.

CSSThe reference to the picture in the file is also replaced with the modified onehashname:
Webpack 4.0 breaking down (3) -- assets

htmlStatic resource reference replacement in file needs to be done throughhtml-loader

2.2 reference optimization

Build tools throughurl-loaderTo optimize the reference path of resources in the project, and set the size limit when the volume of resources is less thanlimitWhen it’s done, it’s done directlyBase64 conversionAfter embedding reference file, the volume is larger thanlimitIt can be passed at the same timefallbackParameterloaderTo deal with.

staywebpack.config.jsAdd inurl-loaderRelated configuration:

{
    test:/\.(jpg|png|svg|gif)/,
    use:[{
      loader:'url-loader',
      options:{
        limit:8129 , // images less than the limit will be converted to the base64 embedded reference location
        Fallback: 'file loader' // if it is greater than the limit, it will be transferred to the specified loader for processing
        Outputpath: 'IMGs /' // options will be passed directly to the loader specified by fallback
      }
    }]
  }

originalCSSReferences to resources in the file:

.with-img{
    background-image: url('../imgs/pic1.png');
}
.with-small-img{
    background-image: url('../imgs/6k.gif');
}

After packing, it changes to the following form. You can see that less than8kIs embedded directly into theCSSFile without generating a separate resource file:
Webpack 4.0 breaking down (3) -- assets

It can also be selected according to the actual needssvg-url-loader,image-webpack-loaderAnd other plug-ins.

2.3 sprites sprite synthesis

Sprite image synthesis sounds like a slightly high-end knowledge point, but it is not necessary. Any technology has its own use scenarios. In some scenarios, the image resources need to be merged into independent sprite images to reduce the number of HTTP requests, and sometimes through theurl-loaderJust embed it in the document. Vector images are processed differently in different scenes.

webpackThe official warehouse does not recommend the image processing tools, but uses theurl-loader + file-loaderAs a general solution of resource processing.

1. Bitmap processing

Bitmap resources, you can usewebpack-spritesmithPlug in processing, in thewebpack.config.jsOfpluginsInstantiate the plug-in in the configuration item and pass in the configuration information

new SpritesmithPlugin({
    //Set the source icon, that is, the path of the icon. Required
    src: {
      cwd: __dirname + '/imgs/pngs',
      Glob: '*. PNG' // regular matching, just follow
    },
    //Set the exported sprite diagram and the corresponding style file. Required
    target: {
      image: __dirname + '/build/imgs/sprite.png',
      css: __dirname + '/build/imgs/sprite.css' 
    },
    //Settings sprite.png You will add your own reference format sprite.css My head
    apiOptions: {
      cssImageRef: './ sprite.png '// cssimageref is required
    },
    //Configure spritismith option, optional
    spritesmithOptions: {
      Algorithm: 'top-down' // sets the arrangement of icons
      Padding: 4 // fill in white space for each small image to avoid bugs in the boundary part of Sprite image
    }
  })

functionwebpackYou can get it latersprites.cssAnd synthetic sprite image:

Sprite.png:

Webpack 4.0 breaking down (3) -- assets

Sprite.css:
Webpack 4.0 breaking down (3) -- assets

2. Vector image processing

The commonly used vector graph in development issvgFormat, both can be usedinline-svg-loaderFor resource embedding, you can also use thesvg-sprite-loaderThe actual situation of the project determines which scheme to combine the vector resources into sprite. The merging principle of vector graph is slightly different from bitmap. Interested readers can search by themselves.

References in source code:

.class1{
    background-image: url('../imgs/svgs/001-home.svg') no-repeat 0 0;
}

useinline-svg-loaderLoader packaged reference:

.class1{
    background-image: url("<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"0 0 16 16\"><path fill=\"#000000\" d=\"M16 9.226l-8-6.21-8 6.21v-2.532l8-6.21 8 6.21zM14 9v6h-4v-4h-4v4h-4v-6l6-4.5z\"></path></svg>") no-repeat 0 0;
}

2.4 image compression and others

Image resources can be compressed with the definition as the quantitative reference,webpackThere are plug-ins available in our development community, but it is not recommended to use themwebpackIn each packaging process, the image itself is processed, which is provided to developers after being processed by UI staff.

The author thinks thatwebpackFor static resources, the first problem to be solved isResource orientationIn addition, other work should be separated from it to shorten the packaging time.

Recommended Today

Practice of query operation of database table (Experiment 3)

Following the previous two experiments, this experiment is to master the use of select statements for various query operations: single table query, multi table connection and query, nested query, set query, to consolidate the database query operation.Now follow Xiaobian to practice together!Based on the data table (student, course, SC, teacher, TC) created and inserted in […]