19

3行代码实现import一个目录下的所有文件

 4 years ago
source link: https://juejin.im/post/5e3cc06951882549327a3add
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

3行代码实现import一个目录下的所有文件

点赞再看,养成习惯,你们的支持是我持续分享的最大动力(^▽^)

最近在做一个理财App,在引入svg图片的时候,起初我是这样子处理的:

import  money from '@/assets/icons/money.svg'
import  labels from '@/assets/icons/labels.svg'
import  statistics from '@/assets/icons/statistics.svg'
复制代码

刚开始只需要引入3svg图片,一个一个引入的话工程量也不是很大,可是后期随着项目的增大,需要引入的文件越来越多,处理起来非常麻烦。

说一句题外话。

什么是高级的程序员?

高级的程序员就是让“问题变得简单”。

于是我花了3个小时,查找我能找到的相关资料,写出了如下解决方案,一次性引入某一目录下相同后缀的所有文件:

 let importAll = (requireContext:__WebpackModuleApi.RequireContext) => requireContext.keys().forEach(requireContext)
    try{
        //经验告诉我,这个代码在单元测试的时候可能会有问题,于是我就加了一个try catch
        importAll(require.context('../assets/icons',true,/\.svg$/));
    }catch(error){
        console.log(error);
    }
复制代码

有了上面三行代码,大大提高了开发的效率,即便后期有再多的svg图片需要引入也不需要担心。

告诫自己,即使再累也不要忘记学习,成功没有捷径可走,只有一步接着一步走下去。 共勉!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK