利用grunt本地管理svg,生成icon.js

需要依赖
grunt
grunt-svgstore 生成svg-sprite
svgo 优化压缩svg

const fs = require('fs');
const path = require('path');

const dir = './svg';

module.exports = function(grunt) {
    grunt.initConfig({
        svgstore: {
            options: {
                prefix : 'icon-', // svg-sprite会以icon-加文件名为id
                svg: {
                    xmlns: 'http://www.w3.org/2000/svg'
                },
                includedemo: false,
            },
            default : {
                files: {
                    [`${dir}/icon-tmp.svg`] : [`${dir}/*.svg`]
                },
            }
        }
    });

    // 优化压缩svg
    grunt.registerTask('compress', function () {
        const config = {
            plugins: [{
                name: 'preset-default',
                params: {
                    overrides: {
                        inlineStyles: {
                            onlyMatchedOnce: false,
                        }
                    }
                }
            }
            ]
        };
        fs.readdir(dir, (err, data) => {
            if (err) {
                console.log(err)
            } else {
                data.forEach(e => {
                    if (e.includes('svg')) {
                        const fileDir = path.join(dir, `${e}`);
                        let svg = fs.readFileSync(fileDir, 'utf-8');
                        const result = svgo.optimize(svg, config);
                        fs.writeFileSync(path.join(dir, `${e}`), result.data, function (err) {
                            if (err) {
                                console.log(err)
                            }
                        })
                    }
                })
            }
        })
    })

    // 生成svg-sprite
    grunt.loadNpmTasks('grunt-svgstore');

    // 生成icon.js
    grunt.registerTask('createIconJs',  function() {
        const template = `!function(c){var a,h,l,t,o, i= '$svgsStr',z=(z=document.getElementsByTagName("script"))[z.length-1].getAttribute("data-injectcss"),s=function(c,a){a.parentNode.insertBefore(c,a)};if(z&&!c.__iconfont__svg__cssinject__){c.__iconfont__svg__cssinject__=!0;try{document.write("<style>.svgfont {display: inline-block;width: 1em;height: 1em;fill: currentColor;vertical-align: -0.1em;font-size:16px;}</style>")}catch(c){console&&console.log(c)}}function m(){o||(o=!0,l())}function p(){try{t.documentElement.doScroll("left")}catch(c){return void setTimeout(p,50)}m()}a=function(){var c,a;(a=document.createElement("div")).innerHTML=i,i=null,(c=a.getElementsByTagName("svg")[0])&&(c.setAttribute("aria-hidden","true"),c.style.position="absolute",c.style.width=0,c.style.height=0,c.style.overflow="hidden",a=c,(c=document.body).firstChild?s(a,c.firstChild):c.appendChild(a))},document.addEventListener?~["complete","loaded","interactive"].indexOf(document.readyState)?setTimeout(a,0):(h=function(){document.removeEventListener("DOMContentLoaded",h,!1),a()},document.addEventListener("DOMContentLoaded",h,!1)):document.attachEvent&&(l=a,t=c.document,o=!1,p(),t.onreadystatechange=function(){"complete"==t.readyState&&(t.onreadystatechange=null,m())})}(window);`
        const svg = fs.readFileSync(path.join(dir, 'icon-tmp.svg'), 'utf-8');
        fs.writeFileSync(path.join(`${dir}`, 'icon.js'), template.replace('$svgsStr', svg))
        fs.unlinkSync(path.join(dir, 'icon-tmp.svg'))
    });
    grunt.registerTask('default', ['compress', 'svgstore', 'createIconJs']);
};

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值