forked from sveltejs/svelte-preprocess
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpostcss.ts
92 lines (79 loc) · 2.26 KB
/
postcss.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
83
84
85
86
87
88
89
90
91
92
import postcss from 'postcss';
import type { Transformer, Options } from '../types';
async function process({
options: { plugins = [], parser, syntax } = {},
content,
filename,
sourceMap,
}: {
options: Options.Postcss;
content: string;
filename?: string;
sourceMap?: string | object;
}) {
const { css, map, messages } = await postcss(plugins).process(content, {
from: filename,
to: filename,
map: { prev: sourceMap, inline: false },
parser,
syntax,
});
const dependencies = messages.reduce((acc, msg) => {
// istanbul ignore if
if (msg.type !== 'dependency') return acc;
acc.push(msg.file);
return acc;
}, [] as string[]);
return { code: css, map, dependencies };
}
async function getConfigFromFile(
options: Options.Postcss,
): Promise<{ config: Options.Postcss | null; error?: string | null }> {
try {
/** If not, look for a postcss config file */
const { default: postcssLoadConfig } = await import(`postcss-load-config`);
const loadedConfig = await postcssLoadConfig(
options,
options?.configFilePath,
);
return {
error: null,
config: {
plugins: loadedConfig.plugins,
// `postcss-load-config` puts all other props in a `options` object
...loadedConfig.options,
},
};
} catch (e: any) {
return {
config: null,
error: e,
};
}
}
/** Adapted from https://github.com/TehShrike/svelte-preprocess-postcss */
const transformer: Transformer<Options.Postcss> = async ({
content,
filename,
options = {},
map,
}) => {
let fileConfig: {
config: Options.Postcss | null;
error?: string | null;
} | null = null;
if (!options.plugins) {
fileConfig = await getConfigFromFile(options);
options = { ...options, ...fileConfig.config };
}
if (options.plugins || options.syntax || options.parser) {
return process({ options, content, filename, sourceMap: map });
}
if (fileConfig?.error != null) {
console.error(
`[svelte-preprocess] PostCSS configuration was not passed or is invalid. If you expect to load it from a file make sure to install "postcss-load-config" and try again.\n\n${fileConfig.error}`,
);
}
return { code: content, map, dependencies: [] as any[] };
};
export { transformer };