neumedia-svg-icon
v1.0.5
Published
使用`svg-sprite-loader`替换默认的`file-loader`加载svg图形:
Downloads
2
Readme
优雅的引入SVG图形
使用svg-sprite-loader
替换默认的file-loader
加载svg图形:
安装插件
安装svg-sprite-loader
:
yarn add svg-sprite-loader
注册组件
将组件文件置于src/components/
目录下;
在src/assets/
目录下建立icons/svg
目录;
配置webpack,打开vue.config.js
,并增加下面内容:
// 重新定义 svg loader,使用 svg-sprite-loader 作为默认 svg 加载器使用
const svgRule = config.module.rule('svg');
svgRule.uses.clear();
svgRule.exclude.add(/node_modules/); // 正则匹配排除node_modules目录
svgRule // 添加svg新的loader处理
.test(/\.svg$/)
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
});
// 重新定义 images loader
const imagesRule = config.module.rule('images');
imagesRule.exclude.add(resolve('src/assets/icons'));
config.module.rule('images').test(/\.(png|jpe?g|gif|svg)(\?.*)?$/);
全局注册svg-icon
组件,打开并修改main.js
文件:
import SvgIcon from '@/components/SvgIcon';
Vue.component('svg-icon', SvgIcon);
const requireAll = requireContext => requireContext.keys().map(requireContext);
const req = require.context('./assets/icons/svg', false, /\.svg$/);
requireAll(req);
组件使用
将svg图片置于src/assets/icons/svg
目录下,如src/assets/icons/svg/demo.svg
。
设置svg图片中的fill属性:
fill="currentColor"
// 或
fill=""
// 或直接删除fill属性
在组件中使用标签svg-icon
对组件进行引用:
<svg-icon iconClass="demo" className="class-name"></svg-icon>