EdwardZZZ / articles

工作点滴记录
2 stars 0 forks source link

file to base64 #35

Open EdwardZZZ opened 6 years ago

EdwardZZZ commented 6 years ago
        const { code, file } = op;
        const { filter, config } = this;

        if (filter.test(file)) {
            const { root, fileLimit = 20 } = config;
            postcss()
                .use(url({
                    url: "inline",
                    encodeType: 'base64',
                    basePath: root,
                    maxSize: fileLimit
                }))
                .process(code)
                .then(result => {
                    result.warnings().forEach(function (warn) {
                        console.warn(warn.toString());
                    });

                    op.code = result.css;
                    op.next();
                });
        }

        // if (filter.test(file)) {
        //     const { root, fileLimit } = config;
        //     const reg = /url\(([^\(\)\s]+.[png|jpg|gif|jpeg])\)/gi;

        //     op.code = code.replace(reg, (...props) => {
        //         const path = props[1];
        //         if (path.indexOf('http') === 0) {
        //             return `url(${path})`;
        //         }

        //         const filePath = root + path;

        //         try {
        //             const file = fs.readFileSync(filePath);

        //             if (fileLimit && file.length > parseInt(fileLimit) * 1024) {
        //                 console.info(`\n${colors.red('[base64] error')} > ${colors.blue(filePath)} is too big.\n`);
        //                 return `url(${path})`;
        //             }

        //             const base64Str = file.toString('base64');
        //             const mimeType = mime.lookup(filePath);

        //             return `url(data:${mimeType};base64,${base64Str})`;
        //         } catch(e) {
        //             console.log(e);
        //             return `url(${path})`;
        //         }
        //     });
        // }