postcss.config.js 2.91 KB
/**
 * postcss plugins for both dev and pro
 * @parem et Symbol
 */
const path = require('path');

exports.postcssPlugin = (et) => {
    let sprites = {
            spritesmith: {
                padding: 8
            },
            filterBy(file) {
            // base64 的图片没有 url 过滤掉
                if (file.url) {
                    return Promise.resolve();
                }
                return Promise.reject();
            },
            groupBy(file) {
                let group = file.url.split('/')[1];
                let entry = path.basename(file.styleFilePath);

                file.retina = true;
                file.radio = 2;

                if (group) {
                    group = entry + '.' + group;
                }

                return group ? Promise.resolve(group) : Promise.reject('yoho');
            }
        },
        assets,
        plugins;

    // assets & sprites config in both dev and pro
    if (et === 'pro') {
        assets = {
            loadPaths: [dist.img, dist.font],
            relativeTo: dist.css
        };

        Object.assign(sprites, {
            basePath: dist.img,
            stylesheetPath: dist.css,
            spritePath: dist.img
        });
    } else if (et === 'dev') {
        assets = {
            loadPaths: [path.join(__dirname, '../img/'), path.join(__dirname, '../font/')],
            relativeTo: path.join(__dirname, './bundle')
        };

        Object.assign(sprites, {
            basePath: path.join(__dirname, '../img/'),
            stylesheetPath: path.join(__dirname, './bundle'),
            spritePath: path.join(__dirname, './bundle')
        });
    }

    plugins = [
        require('postcss-import')({
            path: [path.join(__dirname, '../scss')],
            resolve(id) {
                let name = path.basename(id);

                if (!/^_/.test(name)) {
                    id = path.dirname(id) + '/_' + name;
                }
                return id;
            }
        }),
        require('precss'),
        require('postcss-sprites').default(sprites),
        require('postcss-assets')(assets),
        require('postcss-calc'),
        require('postcss-pxtorem')({
            rootValue: 40,
            unitPrecision: 5, // 保留5位小数字
            minPixelValue: 2, // 小于 2 时,不转换
            selectorBlackList: [], // 选择器黑名单,可以使用正则
            propWhiteList: [] // 属性名称为空,表示替换所有属性的值
        }),
        require('autoprefixer')({
            browsers: ['> 1%']
        }),

        // 可选
        require('postcss-use')({
            modules: ['postcss-clearfix', 'postcss-crip', 'postcss-short', 'postcss-center', 'postcss-position']
        })
    ];

    if (et === 'pro') {
        plugins.push(require('postcss-cachebuster')({
            imagesPath: `/${dist.img}`,
            cssPath: `/${dist.css}`
        }));
    }
    return plugins;
};