-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloader-less-to-css.js
51 lines (49 loc) · 1.3 KB
/
loader-less-to-css.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const path = require('path');
const less = require('less');
const postcss = require('postcss');
const syntax = require('postcss-less');
const atImport = require('postcss-import');
const autoprefixer = require('autoprefixer');
const loader = function (lessContent) {
const cb = this.async();
this.setOutputOptions({
ext: '.css',
});
postcss([
autoprefixer({
// 提升兼容性
overrideBrowserslist: ['last 10 versions'],
}),
atImport({
resolve: (id) => {
const currentPath = this.resource;
if (id.startsWith('@')) {
// 处理别名路径,把 @ 替换成 src
const srcPath = path.join(__filename, './src');
const targetPath = id.replace(/^@/, srcPath);
return targetPath;
} else {
// 处理相对路径
const relativePath = id;
const targetPath = path.resolve(currentPath, '..', relativePath);
return targetPath;
}
},
}),
])
.process(lessContent, { syntax })
.then((result) => {
// less 转 css
less.render(result.content, (err, css) => {
if (err) {
console.error(err);
return;
}
cb(null, css.css);
});
})
.catch((err) => {
console.error(err);
});
};
module.exports = loader;