Related loaders, since files like.png are not JavaScript modules, you need to configure Webpack to use file-loader or url-loader to handle them properly. Projects created through the Vue CLI already have these pre-configured.

The advantages of converting resource urls are as follows:

File-loader can specify where to copy and place resource files, and how to use version hash names for better caching. In addition, this means you can manage image files close to you, and you can use relative paths without worrying about urls at deployment time. With the correct configuration, WebPack will automatically override the file path to the correct URL in the packaged output.

Url-loader allows you to conditionally convert files to inline BASE-64 urls (when the file is less than a given threshold), which reduces the number of HTTP requests for small files. If the number of files exceeds the threshold, the files are automatically submitted to file-loader for processing.

How to convert

File-loader:

 module.exports = {
  module: {
    rules: [{test: /\.(png|jpe? g|gif)$/i,
        loader: 'file-loader'.options: {
          outputPath: 'images'.// Pack the file and put it in the images folder},},],},};Copy the code
const src = require('./file.png'); 
// import SRC from './file.png';
Const SRC = './file.png'
/ / but you can use the online image const SRC = 'https://juejin.cn/file.png'
const img = new Image();
img.src = src;
document.body.appendChild(img);
Copy the code

Packing results:

const src = "images/dbe16934d9c9d889ffe7406967a3b090.png"
const img = new Image();
img.src = src;
document.body.appendChild(img);
Copy the code

Usually, our packaging code is generated in the dist directory, and the files in it are static resources, which are also used as the root directory for deployment. During development, the local path we wrote is relative to the current folder. Therefore, if we write to death directly, an error message will be displayed indicating that the files under the path cannot be found. Therefore, we need to use file-loader to process the file to the correct path.

Note: The difference between url-loader and file-loader is mentioned here. Url-loader converts a relatively small image to a Base64 address, while those relatively large images continue to be processed as the correct path using file-loader.

const src = "data:image/jpeg; Base64, 9 / j / 4 aaqs..."
const img = new Image();
img.src = src;
document.body.appendChild(img);
Copy the code

Usually for performance optimization (pros and cons of converting images to Base64), we add urL-loader processing. Can file-loader and url-loader be used separately? The answer is yes, but it is usually used in conjunction with it. It is not recommended to convert all images to Base64. Sometimes, instead of optimizing, the package size increases.