Like again, form a habit, your support is the biggest motivation for me to continue to share (^▽^)

Recently, I was working on a financial App. When I introduced SVG images, I initially handled them like this:

import  money from '@/assets/icons/money.svg'
import  labels from '@/assets/icons/labels.svg'
import  statistics from '@/assets/icons/statistics.svg'
Copy the code

At the beginning, we only need to introduce 3 SVG images, which is not a huge amount of work if we introduce them one by one. However, as the project grows later, more and more files need to be introduced, which is very troublesome to deal with.

An aside word.

What is an advanced programmer?

Advanced programmers make things easy.

So I spent the next three hours looking up whatever information I could find and came up with the following solution to import all files with the same suffix in a directory at once:

 let importAll = (requireContext:__WebpackModuleApi.RequireContext) = > requireContext.keys().forEach(requireContext)
    try{
        // Experience tells me that this code may have problems during unit testing, so I add a try catch
        importAll(require.context('.. /assets/icons'.true,/\.svg$/));
    }catch(error){
        console.log(error);
    }
Copy the code

With the above three lines of code, you have greatly improved the efficiency of your development, so you don’t have to worry about importing more SVG images later.

Tell yourself that even if you are tired, don’t forget to learn. There is no shortcut to success, only step by step. ‘!