最近在折腾的时候又想写less了,但是换框架了,成了thinkjs,考虑到开发阶段一直编译编译less的情况..最终根据middleware的特点实现了一个超级简单的less中间件。
作用很简单,我想实现的目标也很简单,在html
中正常写css链接,当时请求会被less
中间件拦截,然后根据路径查找less
文件,并进行编译,最终写入到目标css
文件中。
这个只在开发模式下使用,生产环境不需要使用。主要就是方便使用less编写样式。 https://cdn.pixabay.com/photo/2019/12/04/23/34/sheep-4673941__340.jpg
A less middleware for thinkjs 3.0 on development enviroment.
Compiler less file to css when request xxx.css
file in pages.
npm install think-less --save-dev
Modify /src/config/middleware.js
.The less middleware should before resource
middleware.
const less = require('think-less');
const path = require('path');
const isDev = think.env === 'development';
module.exports = [
{
handle: less,
enable: isDev ? true : false,
options: {
root: path.join(think.ROOT_PATH, 'res'),
target: path.join(think.ROOT_PATH, 'www'),
lessOptions: {
paths: [path.join(think.ROOT_PATH, 'res')],
compress: true
}
}
}
]
代码也很简单,直接使用的less
的模块进行编译,如下:
//thinkjs middleware of less compiler
const less = require('less');
const path = require('path');
const fs = require('fs');
const mkdirsp = require('mkdirsp');
module.exports = (options,app)=>{
return async (ctx,next)=>{
let extname = path.extname(ctx.path);
if(extname.toLowerCase() != '.css'){
return next();
}
let filePath = path.join(options.root,ctx.path.substr(0,ctx.path.indexOf('.css'))+'.less');
let targetPath = path.join(options.target,ctx.path);
if(!fs.existsSync(filePath)){
return next();
}
let content = Buffer.from(fs.readFileSync(filePath)).toString('utf8');
try{
await mkdirsp(path.dirname(targetPath));
let out = await less.render(content,options.lessOptions)
fs.writeFileSync(targetPath,out.css);
}catch(e){
return Promise.reject(e);
}
return next();
}
}
转载请注明出处: https://chrunlee.cn/article/think-js-less-middleware.html