Look at the specific processing process webpack css file path into the picture through the phenomenon

webpack is currently the more popular a front-end module packer, any resources have been treated as a front-end modules to handle, such as images, css files, and so on. In the front of the building project based webpack, usually configured rules regarding css file handling, which also includes processing resources css file picture, then webpack in the end it is how to deal with it? Also encountered similar problems before the author's picture Road King, this also wrote a blog post webpack generated css file background-image url picture could not be loaded . Today it said webpack is how to deal with the image path css file, first on a concrete example.

A specific issue

Recent umi a project to build a front end, you may encounter a bug umi during use, this also raises the issue project configuration module affect css to css-loader handling of third-party libraries css file picture the url . Incidentally, in the description:

  • In the project by setting cssLoaderOptions.modulesto open css module to true

  • Project was introduced in third-party libraries kindeditor css file.

    import 'kindeditor/themes/default/default.css'

    The file has default.css by urlintroducing image resource, and the non-image resources relative path wording, for example, where a writing of:

      .ke-toolbar-icon-url {
       background-image: url(background.png);
      }

Then npm start the open local services preview, compile error, as shown below:

Strange, obviously the corresponding picture resource is there, why not find webpack when compiling it? I pondered a lot of hard not found the answer, then dove into the ocean webpack and css-loader in open-source "treasure hunt" tour.

Sell ​​to do with the child, leading to the direct cause of the above:

css css-loader file no urltreatment method (converted to a relative path)

This results in the integration of webpack after the loader default.css processing module, because the module is used require(background.png)to reference the image resource, then you use the module loading mechanism Nodejs, the specific can view this blog in another article to talk about dependence npm management can also view nodejs official network module section . When parsing nodejs background.png image path, the third party will parse module, it will from the node_moduleslookup, by printing the error log webpack, wherein some clues can be seen, as shown below, to find ever field indicates Missing path did not find corresponding resource file.

In fact, using the internal umi css-loader-1(fork [email protected] from) to handle the css file, causing css-loaderthe underlying reason for no css file path to the image processing of:

Project open css module , the case should not affect the css files css node_modules in the module and in fact had an impact; resulting in no css file to a third-party library for processing in the image path

webpack is how the conversion path to the image in the css?

If you simply in order to solve the above problem can stop here, but in a curious, after all, is the pit a few times, want to know is how to deal with the image path webpack css file of. For example, we wrote this css in the project:

.xxa {
    background: url(background.png)
}

Or this:

.xxb {
    background: url(~alias/background.png)
}

In the project, whether we write css use less, stylus or the like css sass pretreatment library, which ultimately by the corresponding loader, such as less-loader conversion pattern is converted into the prepared css, then css-loaderto the conversion process in association with a route css its role to take its official website describes it:

The css-loader interprets @import and url() like import/require() and will resolve them.

The most common treatment css styles projects, usually after several loader from right to left order of execution, style take less prepared for the show in the form of inline loader to illustrate:

!!css-loader!post-loader!less-loader!./xxx/xx.less

Of course, even after the css-loader processing style-loader or Mini-CSS-Extract-plugin Loader treatment provided, but this is not the scope of this talk.

By following a picture to look after webpack parsing module to css output of this process, webpack help us to do something.

Specifically for a simple analysis of the entire process, the analysis may have not the right place, but also please criticism

NormalModuleFactory parsing and creating modules

  • First, start building from the entrance file (file entry configuration), use NormalModuleFactory to parse and create a module

  • NormalModuleFactory use enhance-resolvemodule absolute addresses to resolve dependencies, if the module address issues such as parsing errors will throw an error at the beginning of the article, it will create a dependency resolved correctly module. The figure above ./index.css , the module address resolution succeeds, module properties webpack created for index.css follows:

    Create a module, generally including the module type, context, request, userRequest, rawRequest, resource, dependencies and loaders and other information about the module.

    After the module is created, with its dependence treatment loader to compile the module content, module dependent loader in the property array loader module; for css files and finally use css-loaderto deal with.

css-loader css files compiled

css-loader's official website said the css file will url/@importbe processed, but the specific implementation details and did not elaborate. Let's briefly the main functions of the css-loader:

  • The conversion css urland @importis require/import;

    For example, urlthe address (except absolute address) will be parsed as a relative address, to prevent mistakes during parsing module WebPACK address; which comprises WebPACK Alias Address and alias addresses node_moduels libraries thereof. by the way:

    by internal css-loader postcssto complete the conversion generated css ast and traverse the method to find out the url .

  • Css file content generation module in the form of modules comonjs

    commonjs modular form css file after the final conversion, the module or suffixes .css , which is shown as follows:

  • css-loader further processing css module, the conversion is accomplished by traversing the css ast

This completes the picture url css file conversion path through css-loader, webpack help find the specific location of the picture resources.

url-loader with pictures resources

In fact, the processed css css-loader module process, will be created and its internal parse module again through the image NormalModuleFactory, webpack module corresponding attribute follows:

Generating a module corresponding to the image content may be content commonjs base64, as shown below:

Also may reference address, as shown in a picture resource output:

It depends on whether the specified url-loader when processing image resource limitconfiguration item value, which is compared with the picture content size. The limitvalue is smaller than the size of the picture content, using file-loaderraised to the position corresponding to webpack compiled output image is achieved.

The above picture is a picture output module content address, it is the file-loaderresult of the process, its implementation following functions:

  • Picture content will be pulled to webapck compiler output location.

  • The loader according to namethe configuration of webpack and publicPathgenerate the final configuration item url.

    Because the content is pulled out of the picture, then webpack-generated image module content should reference address for the picture. This involves two parts

    • The relative address generating section configuration item name of file-loader.

      File-loader configuration items as follows:

    {
     test: /\.(png|jpe?g|gif)$/i,
     loader: 'file-loader',
     options: {
     name: 'static/[name].[hash:8].[ext]',
     },
    }

    Then according loader-utilsto interpolateNameanalytical methods corresponding to url. For example picture above address css file conversion results:

    ./background.pngWill be converted to: static/background.a9153e95.png

    • According to webpackConfig.output.publishPaththe reference address generated picture.

      The final generated address is:

      __webpack_public_path__ + "static/background.a9153e95.png";

After processing the above steps, we see the effect of the final output css file as shown below:

By the way, if the output of the css file through the mini-css-extract-pluginloader provides unified pulled, it may also affect the css file picture reference path, especially the loader configuration of publicPathcontent, such as the following loader configuration:

{
   loader: MiniCssExtractPlugin.loader,
   options: {
     publicPath: 'public/path/to/'
   }
}

Then the path css file picture of the final results as shown below:

This is the process through various loader webapck processing images in css Road King, and through this process we may just have a general knowledge about this process, or if you want in-depth understanding of the need to spend time to study.

references

Published 132 original articles · won praise 15 · views 10000 +

Guess you like

Origin blog.csdn.net/ling_76539446/article/details/104198291