编程知识 cdmana.com

Webpack 4.0 breaking down (3) -- assets

One . Assets Basic processing requirements of resources

Assets, Refers to the referenced resources in the project , Usually for various formats of pictures and font files , Of course, it can also contain a variety of other extensions (.json,.xml etc. ), Common image and text resource processing includes :

  • Volume compression
  • Sprite chart merge and reference correction
  • The reference path of the resource is automatically replaced

Two . webpack Dealing with reference resources

2.1 Resource Package

webpack adopt file-loader Processing resource files , It will be rules Rules hit the resource file according to the configuration information ( route , Name, etc ) Output to the specified directory , And return its resource location address ( The output path , For the production environment publicPath route ), The default output name is calculated based on the content of the original file MD5 Hash Named .

stay webpack.config.js Add processing rules for image files in :

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

Execute the pack command to see png The name of the image resource is replaced with hash And output to the build folder .

CSS The reference to the picture in the file is also replaced by the modified hash name :

html The static resource reference replacement in the file needs to be done through html-loader.

2.2 Citation optimization

Build tools through url-loader To optimize the reference path of resources in the project , And set the size limit , When the volume of a resource is less than limit When it's done Base64 transformation After embedding the reference file , Volume greater than limit You can go through fallback Parameter specified loader To deal with .

stay webpack.config.js Add url-loader Related configuration :

  {
    test:/\.(jpg|png|svg|gif)/,
    use:[{
      loader:'url-loader',
      options:{
        limit:8129,// Less than limit Restricted images will be converted to base64 Embedded reference location 
        fallback:'file-loader',// Greater than limit The restricted will be transferred to the designated loader Handle 
        outputPath:'imgs/'//options It'll go straight to fallback designated loader
      }
    }]
  }

original CSS A reference to a resource in a file :

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

After packing, it becomes the following form , You can see less than 8k Resources are embedded directly into CSS File without generating a separate resource file :

You can also choose according to the actual needs svg-url-loader,image-webpack-loader And other plug-ins .

2.3 sprites Composite sprite

Composite sprite , It sounds like a slightly high-end knowledge point , But it doesn't have to be , Any technology has its own use scenarios . In some scenes, it is necessary to merge the image resources into independent sprite images to reduce http Number of requests , Sometimes, maybe through url-loader Just embed it in the document . Vector images are processed differently in different scenes .

webpack There is no recommended image processing tool in the official warehouse , instead url-loader + file-loader As a general solution of resource processing .

1. Bitmap processing

Bitmap resources , have access to webpack-spritesmith Plug in processing , stay webpack.config.js Of plugins Instantiate the plug-in in the configuration item and pass in the configuration information :

  new SpritesmithPlugin({
    // Set source icons, namely icon The path of , Will options 
    src: {
      cwd: __dirname + '/imgs/pngs',
      glob: '*.png' // Regular matching , Just fill it in 
    },
    // Set the exported sprite Corresponding files and styles , Will options 
    target: {
      image: __dirname + '/build/imgs/sprite.png',
      css: __dirname + '/build/imgs/sprite.css' 
    },
    // Set up sprite.png The quotation format of , I'll join myself sprite.css The head of 
    apiOptions: {
      cssImageRef: './sprite.png' //cssImageRef It's a must 
    },
    // To configure spritesmith Options , Non essential election 
    spritesmithOptions: {
      algorithm: 'top-down',// Set the arrangement of the icons 
      padding: 4 // Fill in the blanks in each picture , Avoid the boundary part of Sprite bug
    }
  })

function webpack And then you can get sprites.css And synthetic sprite :

Sprite.png:

Sprite.css:

2. Vector processing

The commonly used vector graph in development is svg Format , Both available inline-svg-loader Resource embedding , You can also use svg-sprite-loader Merge vector resources into sprite , What is the specific scheme to be adopted , It needs to be judged by the actual situation of the project . The merging principle of vector graph is slightly different from bitmap , Interested readers can search for .

References in source code :

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

Use inline-svg-loader Loader 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 other

Image resources can be compressed in terms of definition ,webpack There are plug-ins available in our development community , But it is not recommended to pass webpack The image itself is processed at each packaging time , But by the UI It is provided to the developers after being handled by the developers .

The author thinks webpack The first problem to be solved for static resources is Resource positioning , In addition, other work should be separated from it , To shorten the packing time .

author : Dashi doesn't talk
link :webpack4.0 Crush one by one (3)—— Assets piece
source : Blog Garden
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .

版权声明
本文为[GZXZSJ]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225142123824X.html

Scroll to Top