在前端开发中,我们经常需要使用 CSS 预处理器来简化样式表的编写。Less 是一种比较流行的 CSS 预处理器之一,它提供了很多便捷的语法和功能。
在 Egg.js 项目中,我们需要使用到 Less 来编译样式文件。但是,Egg.js 并没有默认集成 Less 编译功能,需要我们手动配置。因此,我决定造一个 Egg.js 插件,用于集成 Less 编译功能,方便后续开发使用。
插件设计思路
在设计插件前,我们需要明确几个问题:
- 插件需要实现哪些功能?
- 插件如何与 Egg.js 框架整合?
针对第一个问题,我们可以列出以下需求:
- 自动编译 Less 文件并输出 CSS 文件。
- 支持 Less 的变量、嵌套、混入等语法特性。
- 支持自定义 Less 编译选项,例如压缩等级。
- 支持监听 Less 文件变化,并自动重新编译。
针对第二个问题,我们可以通过 Egg.js 提供的插件机制来实现集成。具体来说,我们需要完成以下步骤:
- 在应用启动时加载插件。
- 在插件中注册路由,以便应用能够访问编译后的 CSS 文件。
- 在插件中添加编译 Less 文件的逻辑,并在需要时调用。
插件实现步骤
创建 Egg.js 项目,并安装 Less 和 chokidar(用于监听文件变化)依赖:
npm init egg --type=simple npm i -S less chokidar
在
config/plugin.js中添加 Less 插件配置:exports.less = { enable: true, package: 'egg-less', };这里通过
egg-less插件来集成 Less 功能。在
config/config.default.js中添加 Less 编译选项:exports.less = { // 自定义编译选项 options: { compress: true, }, };在
app/router.js中注册路由,以便应用能够访问编译后的 CSS 文件:module.exports = app => { const { router, controller } = app; router.get('/static/*.css', controller.static.serve); };这里通过
app/controller/static.js控制器来处理静态文件请求:// www.javascriptcn.com code example const path = require('path'); const sendToWormhole = require('stream-wormhole'); class StaticController extends Controller { async serve() { const { ctx } = this; const file = ctx.params[0]; const filePath = path.join(this.config.baseDir, 'app/public', file); try { await send(ctx, filePath); } catch (err) { if (err.status !== 404) { throw err; } ctx.response.status = 404; ctx.response.body = '404 Not Found'; } } } module.exports = StaticController;在
app.js中添加编译 Less 文件的逻辑,并在需要时调用:// www.javascriptcn.com code example const chokidar = require('chokidar'); const less = require('less'); class AppBootHook { constructor(app) { this.app = app; } async didLoad() { // 监听 less 文件变化 chokidar.watch(this.app.config.less.srcPath).on('all', (event, path) => { this.compileLess(path); }); } async compileLess(file) { const { app } = this; try { const options = app.config.less.options || {}; const result = await less.render(await fs.readFile(file, 'utf8'), options); const cssFile
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/31926