-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
86 lines (74 loc) · 2.6 KB
/
index.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
'use strict';
const Path = require('path');
const stylus = require('stylus');
const { isString, isBoolean } = require('celia');
const { forOwn } = require('celia').object;
const { toKoa } = require('kyla/middleware');
const { relativeWith } = require('kyla/path');
const moduleRequestRegex = /^[^?]*~/;
const currentDir = process.cwd();
module.exports = (stylusOptions) => {
// 处理成绝对路径
relativeWith(stylusOptions, [
'src',
'dest',
'import',
'url.paths'
]);
// 默认一个编译函数
if (!stylusOptions.compile) {
stylusOptions.compile = (str, path) => {
// 编译后css的路径
const newStylus = stylus(str).set('filename', path);
if (stylusOptions.sourcemap) {
if (isBoolean(stylusOptions.sourcemap)) {
stylusOptions.sourcemap = {};
}
stylusOptions.sourcemap.inline = true;
}
newStylus
.set('compress', stylusOptions.compress)
.set('firebug', stylusOptions.firebug)
.set('linenos', stylusOptions.linenos)
.set('sourcemap', stylusOptions.sourcemap);
// 内置url函数至stylus文件中
const inlineUrl = stylusOptions.url;
if (inlineUrl) {
if (isString(inlineUrl)) {
newStylus.define(inlineUrl, stylus.url());
} else {
inlineUrl.limit = inlineUrl.limit || 30000;
inlineUrl.paths = inlineUrl.paths || [];
newStylus.define(inlineUrl.name || 'inline-url', stylus.url(inlineUrl));
}
}
// 默认支持导入css
if (stylusOptions.includeCSS !== false) {
newStylus.set('include css', true);
}
// 支持全局变量和全局函数
const defineObj = (stylusOptions.define || {});
forOwn(defineObj, (val, key) => newStylus.define(key, val));
// 定义stylus的原生函数
const rawDefineObj = (stylusOptions.rawDefine || {});
forOwn(rawDefineObj, (val, key) => newStylus.define(key, val, true));
// 导入styl文件后,全局可访问styl里面的东西
if (Array.isArray(stylusOptions.import)) {
stylusOptions.import.forEach((plugin) => {
if (moduleRequestRegex.test(plugin)) {
plugin = plugin.replace(moduleRequestRegex, Path.join(currentDir, '/node_modules/'));
}
newStylus.import(plugin);
});
}
// 导入一些插件库nib或者poststylus等
if (Array.isArray(stylusOptions.use)) {
stylusOptions.use.forEach((plugin) => {
newStylus.use(plugin);
});
}
return newStylus;
};
}
return toKoa(stylus.middleware(stylusOptions));
};