vue dynamic loading image path error solution

 

Recently encountered the problem of image path loading error

I have always put pictures under the assets file. Always report an error, see some articles and try successfully, specially record it

First of all, let's explain the difference between the assets and static files of vue-cli, because this will help you understand the following solutions.

 assets: In the process of project compilation, it will be processed and resolved into module dependencies by webpack, and only supports the form of relative paths, such as < img src=”./logo.png”> and background:url(./logo.png),” ./logo.png" is a relative resource path, which will be resolved by webpack as module dependency 
 static: files in this directory will not be processed by webpack, which simply means that the place where third-party files are stored will not be resolved by webpack. It will be copied directly to the final packaging directory (dist/static by default). These files must be referenced using absolute paths, as determined by the build.assetsPublic and build.assertsSubDirectory links in the config.js file. Any file placed in static/ needs to be referenced in the form of an absolute path: /static[filename] 
 According to the characteristics of webpack, in general, static placement will not change, third-level files, asserts place files that may change

Here comes the problem, use js to dynamically load assets or the picture of this file has a 404 status code

When running, I found that the picture is not displayed, the error code is 404, the 
 reason: the picture picture is used as a module in webpack, because it is loaded dynamically, so the url-loader will not be able to parse the picture address, and then npm run dev or npm run After the build, the path is not processed [the path parsed by webpack will be parsed as /static/img/[filename].png, and the full address is localhost:8080/static/img/[filename].png] 
 Solution: ① Load the image as a module, such as images:[{src:require('./1.png')},{src:require('./2.png')}] so that webpack can parse it. ②Put the image in the static directory, but it must be written as an absolute path such as images:[{src:”/static/1.png”},{src:”/static/2.png”}] and the image will also be displayed , of course, you can also shorten the writing length of the path by defining it in webpack.base.config.js.

 

 This is a screenshot of the article I saw, but I found that as long as the image file is directly placed in the static file, it is also possible to write a relative path.

If you have any questions, welcome to discuss~~~

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324807161&siteId=291194637