onvno / pokerface

日常技术文章阅读整理
3 stars 0 forks source link

20190325 - es6中引入多个图片文件 #9

Open onvno opened 5 years ago

onvno commented 5 years ago

原方法

import downIcon1 from 'ASSETS/downIcon1.png';
import downIcon2 from 'ASSETS/downIcon2.png';
import downIcon3 from 'ASSETS/downIcon3.png';
import downIcon4 from 'ASSETS/downIcon4.png';

            if (item === '0') {
              current.symbol = `image://${downIcon1}`;
            } else if (item === '1') {
              current.symbol = `image://${downIcon2}`;
            } else if (item === '2') {
              current.symbol = `image://${downIcon3}`;
            } else if (item === '3') {
              current.symbol = `image://${downIcon4}`;
            }

改善后

使用webpack提供的方法:require.context。 说明:图片转为base64,存储到对象中 坑:正则匹配只识别以xx结尾,不能正常识别开头和结尾的匹配 优点:可以使用alias别名

function importAll(r) {
  let images = {};
  r.keys().map((item, index) => { 
    console.log(item, index)
    images[item.replace('./', '')] = r(item); 
  });
  console.log("images:", images);
  return images;
}
const images = importAll(require.context('ASSETS', false,  /(downIcon|upIcon)\S*\.png$/));

const downIconImage = images[`downIcon${parseInt(item) + 1}.png`]
 current.symbol = `image://${downIconImage}`

扩展

可以用来省去重复工作,如vue组件加载 Webpack中的require.context妙用

// plugins/component.js
export default {

    install(Vue){
        const context = require.context('../components', true, /\.vue/)
        context.keys().forEach(key => {
            const component = context(key).default
            Vue.component(component.name, component)
        })
    }
}

// app.js
import Vue from 'vue'
import globalComponents from './plugins/components'
Vue.use(globalComponents)

参考来自:

补充:

es6函数默认值 function(a = 123, b ){ }