This time I will bring youpicturesHow to deal with webpack packaging errors caused by paths, what are theprecautionswhen dealing with image paths causing webpack packaging errors, the following is a practical case, let’s take a look take a look.
I recently encountered such a problem when I was making my own personal blog. I used a relative path in CSS to serve as a background image, as shown below:
Then after packaging the entire project using webpack, an error is reported when running on the browser. The error is as follows:
In other words, the image file cannot be found after packaging. Here we are, so what’s the reason? Let’s first take a look at my configuration in the webpack.config.js file:
In fact, my loader is not used incorrectly here. Yes, the corresponding image is processed using url-loader. Then let’s take a look at the directory after packaging through webpack:
We found that the file we want to package appears in the dist folder A file build.js is generated, and an additional image file is also generated. This file is the background image we just specified in CSS
. You can find it through the browser error message, build.js The address of the image specified for us is obviously incorrect. By default, the packaging process will
copy the image used and place it in the directory specified by the path of the output. However, in build.jsThe image path referenced byis indeed the root directory of the entire project file, so the natural reference
is not used. So how should we deal with it? In the webpack.config.js file, outputobject The publicPathattributeis specified in, which is used to specify the publishing address ofstaticresources (pictures, etc.). When this attribute is configured, the file is packaged (That is, build.js) All resources referenced by relative paths will be replaced by the configured paths. Therefore, after setting
like this, the path referencing the image in build.js will add the path specified by publicPath after the path of the initial root directory, so we add
## in webpack.config.js #The content in the red box in the picture below is enough:
Then in the end, you can run it through the dist folder Found the generated image!
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:How webpack dynamically introduces files
What needs to be done with webpack to package specified JS files
The above is the detailed content of How to deal with webpack packaging errors caused by image paths. For more information, please follow other related articles on the PHP Chinese website!