此篇為webpack處理文件內(nèi)容——babel插件保姆級教學(xué)姐妹篇
前言
本文旨在編寫出postcss8.0插件眶诈,將css中的http:
替換成https:
亮元。
AST
把代碼轉(zhuǎn)成AST:https://astexplorer.net/#/2uBU1BLuJ1
- 代碼
.hello {
color: green;
font-size: 64px;
background:url(http://xxxxxxx) no-repeat fixed;
background-size: 100% auto;
}
-
AST
background
我們要分析的這個backaground節(jié)點的type為decl。
- AST節(jié)點類型
實際上PostCSS將CSS解析為節(jié)點樹之后扁位,節(jié)點有5種type
Root
:樹頂部的節(jié)點鸣奔,代表CSS文件虱痕。
AtRule
:語句以@
like@charset "UTF-8"
或@media (screen) {}
。開頭
Rule
:內(nèi)部帶有聲明的選擇器钝尸。例如input, button {}
括享。
Declaration
:鍵值對,例如color: black
珍促;
Comment
:獨立評論铃辖。選擇器中的注釋,規(guī)則參數(shù)和值存儲在節(jié)點的raws
屬性中猪叙。
————
為什么要更新postcss呢娇斩?
postcss 8.0有好多很棒的改進,詳細(xì)的看PostCSS 8.0:Plugin migration guide穴翩。
比如之前運行插件犬第,即使只改了一點點,它也會遍歷CSS包的整個抽象語法樹芒帕,如果有很多個PostCSS插件就會遍歷很多次歉嗓,速度慢。
所以這次的大版本還是十分值得更新的背蟆。
————
配置
我的插件叫postcss-tran-http-plugin鉴分,這個postcss-
是那個官方文檔強調(diào)的命名方式。
- 特別地
現(xiàn)在postcss 8.0改變了寫插件的方式带膀,如果之前項目有裝過postcss冠场,可以卸了裝個新的。
npm uninstall postcss
npm install postcss --save-dev
- webpack.config.js
use的執(zhí)行順序是右到左
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader', 'postcss-loader'],
},
]
}
- package.json
{
"peerDependencies": {
"postcss": "^8.0.0"
}
}
peerDependencies是為了cover這個場景:
有人要用我寫的postcss插件本砰,需要安裝postcss
碴裙。用這個方法去指定我所要求的那個postcss
版本,以避免版本不匹配可能造成的bug。
- postcss.config.js
之前這個plugins是個對象舔株,打包出錯特地翻了一下文檔才發(fā)現(xiàn)變成數(shù)組了莺琳。
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;
-
簡單說一下
跟babel插件一樣,針對不同的type類型有不同的處理函數(shù)载慈。
上面我們說到這個節(jié)點類型為Declaration惭等,也就是鍵值對。
讀值用decl.value办铡,然后給他直接賦值成新的值就ok了辞做。
結(jié)果
- 代碼
// style.css
body {
background: darkcyan;
}
.hello {
color: green;
font-size: 64px;
background:url(http://xxxxxxx) no-repeat fixed;
background-size: 100% auto;
}
-
打包后
寫postcss插件其實還好,節(jié)點類型不多寡具,修改也簡單秤茅。
值得關(guān)注的就是升級到8.0之后postcss.config.js
、插件編寫童叠、依賴庫的引用都有變動框喳。
參考:
今天!從零開始調(diào)試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