-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
82 lines (80 loc) · 2.38 KB
/
index.ts
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
// rollup-plugin-inline-postcss.js
import * as findup from 'findup';
import * as path from 'path';
import { createFilter } from 'rollup-pluginutils';
const postcss = require('postcss');
export default function inlinePostCSS(options: any = {}) {
const filter = createFilter(options.include, options.exclude);
const styleRegex = options.styleRegex
? options.styleRegex
: /(css\`((.|\n)*)\`)/g;
const hasCustomRegex = options.styleRegex ? true : false;
return {
name: 'inline-postcss',
transform(code, id) {
if (!filter(id)) {
return;
}
if (!code.match(styleRegex)) {
return;
}
let punc = code.match(styleRegex)[0][
code.match(styleRegex)[0].length - 1
];
if (punc !== ',' && punc !== ';') {
punc = null;
}
try {
let configFolder;
if (!options.plugins) {
configFolder = findup.sync(__dirname, 'postcss.config.js');
} else {
configFolder = '';
}
const config = options.plugins
? options.plugins
: require(path.join(configFolder, 'postcss.config.js'))({
env: process.env.NODE_ENV,
});
let css = code.match(styleRegex)[0];
if (options.escapeTemplateString || !hasCustomRegex) {
css = css.split('`')[1];
}
const opts = {
from: options.from ? path.join(process.cwd(), options.from) : id,
to: options.to ? path.join(process.cwd(), options.to) : id,
map: {
inline: false,
annotation: false,
},
};
const outputConfig = options.plugins
? options.plugins
: Object.keys(config.plugins)
.filter((key) => config.plugins[key])
.map((key) => require(key));
return postcss(outputConfig)
.process(css, opts)
.then((result) => {
code = code.replace(
styleRegex,
`\`${result.css}\`${punc ? punc : ''}`,
);
const map = result.map
? JSON.parse((result as any).map)
: { mappings: '' };
return {
code,
map,
};
});
} catch (error) {
if (options.failOnError) {
this.error(error.message);
} else {
this.warn(error.message);
}
}
},
};
}