更新于 2024/02/28
今天在Github看到了一个新的hexo tailwind插件,详细讲解了Hexo配置tailwind的方式。非常不错,适合开发者们快速配置及上手。
如果在按照教程升级后遇到了Error: Cannot find module 'node:path'
的报错,请将Node版本升级到v14.18.0以上即可解决。
众所周知,tailwindcss通过原子类的方式,进一步缩小了css体积和避免了起名障碍(有时候想出一个确切的名字属实有点难)。而hexo官网的模板绝大多数都是通过类名的方式来设置页面样式的,使用tailwindcss来构建页面的模板项目近乎没有(实际上在寻找过程中,也没有找到使用tailwindcss的模板案例)。
此处就来讲讲基于tailwindcss的hexo模板应用,在之前搜索hexo+tailwind的过程中,我找到了一个第三方插件:hexo-renderer-tailwindcss。插件源码比较简单,分析了下大概是这两个个步骤:
(1) 安装tailwind相关依赖
1
| npm install postcss postcss-import postcss-load-config tailwindcss
|
(2) 注册hexo渲染钩子,配置postcss处理.css文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 'use strict'
var postcss = require('postcss') var postcssrc = require('postcss-load-config')
module.exports = function (data) { return postcssrc().then(({ plugins, options }) => postcss(plugins).process(data.text, options)) .then((result) => result.css) }
hexo.extend.renderer.register('css', 'css', renderer)
|
同时在进行以上步骤之后,还需要在Hexo根目录下创建postcss的配置文件.postcssrc.js
。此时Hexo就已经完成tailwind的集成工作。
1 2 3 4 5 6 7 8
| module.exports = { from: undefined, plugins: { 'postcss-import': {}, 'tailwindcss': {}, 'autoprefixer': {}, } }
|
但是编写/使用不同主题时,并不是每个主题都需要使用postcss的,那么能不能仅针对某个模板来设置使用tailwind呢?换言之,能否把配置文件集成到模板目录下,而非项目根目录?
经过与ChatGPT的一番友好交流,确认该操作是可行的,改动见下方代码注释:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 'use strict'
const postcss = require('postcss') const postcssrc = require('postcss-load-config')
const customConfigPath = 'themes/****/.postcssrc.js'
function renderer (data) { return postcssrc({}, customConfigPath).then(({ plugins, options}) => postcss(plugins).process(data.text, options)) .then((result) => result.css) }
hexo.extend.renderer.register('css', 'css', renderer)
|
这样就完成了仅针对单个模板配置tailwind和postcss,后续切换其他模板时也方便移除模板内容及相关npm package依赖项。