webpack处理文件内容——编写postcss8.0插件

2020-10-30  本文已影响0人  景阳冈大虫在此

此篇为webpack处理文件内容——babel插件保姆级教学姐妹篇

前言

本文旨在编写出postcss8.0插件,将css中的http:替换成https:

AST

把代码转成AST:https://astexplorer.net/#/2uBU1BLuJ1

.hello {
    color: green;
    font-size: 64px;
    background:url(http://xxxxxxx) no-repeat fixed;
    background-size: 100% auto;
}

Root:树顶部的节点,代表CSS文件。
AtRule:语句以@like@charset "UTF-8"@media (screen) {}。开头
Rule:内部带有声明的选择器。例如input, button {}
Declaration:键值对,例如color: black
Comment:独立评论。选择器中的注释,规则参数和值存储在节点的raws属性中。

————
为什么要更新postcss呢?
postcss 8.0有好多很棒的改进,详细的看PostCSS 8.0:Plugin migration guide

比如之前运行插件,即使只改了一点点,它也会遍历CSS包的整个抽象语法树,如果有很多个PostCSS插件就会遍历很多次,速度慢。

所以这次的大版本还是十分值得更新的。
————

配置

我的插件叫postcss-tran-http-plugin,这个postcss-是那个官方文档强调的命名方式。

npm uninstall postcss
npm install postcss --save-dev
module: {
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader', 'postcss-loader'],
            },
        ]
}
{
  "peerDependencies": {
    "postcss": "^8.0.0"
  }
}

peerDependencies是为了cover这个场景:
有人要用我写的postcss插件,需要安装postcss。用这个方法去指定我所要求的那个postcss版本,以避免版本不匹配可能造成的bug。

module.exports = {
    plugins: [
          require('./plugins/postcss-tran-http-plugin.js')
    ]
}

插件编写

module.exports = (opts) => {
    return {
        postcssPlugin: 'postcss-tran-http-plugin',
        Declaration(decl) {
            console.log('Declaration');
            let oldVal = decl.value;
            if (oldVal.match(/http:\/\/([\w.]+\/?)\S*/)) {
                let newVal = oldVal.replace(/http:\/\//g, 'https://');
                decl.value = newVal;
            }
        },
    };
};
module.exports.postcss = true;

结果

// style.css 
body {
    background: darkcyan;
}
.hello {
    color: green;
    font-size: 64px;
    background:url(http://xxxxxxx) no-repeat fixed;
    background-size: 100% auto;
}

写postcss插件其实还好,节点类型不多,修改也简单。
值得关注的就是升级到8.0之后postcss.config.js、插件编写、依赖库的引用都有变动。

参考:
今天!从零开始调试webpack PostCSS插件
Writing a PostCSS Plugin
http://echizen.github.io/tech/2017/10-29-develop-postcss-plugin
https://www.cnblogs.com/wonyun/p/9692476.html

上一篇 下一篇

猜你喜欢

热点阅读