/
postcss.js
77 lines (64 loc) 路 2.12 KB
/
postcss.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
const localRequire = require('../utils/localRequire');
const loadPlugins = require('../utils/loadPlugins');
const postcss = require('postcss');
const semver = require('semver');
module.exports = async function(asset) {
let config = await getConfig(asset);
if (!config) {
return;
}
await asset.parseIfNeeded();
let res = await postcss(config.plugins).process(asset.getCSSAst(), config);
asset.ast.css = res.css;
asset.ast.dirty = false;
};
async function getConfig(asset) {
let config = await asset.getConfig(
['.postcssrc', '.postcssrc.js', 'postcss.config.js'],
{packageKey: 'postcss'}
);
let enableModules =
asset.options.rendition && asset.options.rendition.modules;
if (!config && !asset.options.minify && !enableModules) {
return;
}
config = config || {};
if (typeof config !== 'object') {
throw new Error('PostCSS config should be an object.');
}
let postcssModulesConfig = {
getJSON: (filename, json) => (asset.cssModules = json)
};
if (config.plugins && config.plugins['postcss-modules']) {
postcssModulesConfig = Object.assign(
config.plugins['postcss-modules'],
postcssModulesConfig
);
delete config.plugins['postcss-modules'];
}
config.plugins = await loadPlugins(config.plugins, asset.name);
if (config.modules || enableModules) {
let postcssModules = await localRequire('postcss-modules', asset.name);
config.plugins.push(postcssModules(postcssModulesConfig));
}
if (asset.options.minify) {
let [cssnano, {version}] = await Promise.all(
['cssnano', 'cssnano/package.json'].map(name =>
localRequire(name, asset.name).catch(() => require(name))
)
);
config.plugins.push(
cssnano(
(await asset.getConfig(['cssnano.config.js'])) || {
// Only enable safe css transforms if cssnano < 4
// See: https://github.com/parcel-bundler/parcel/issues/698
// See: https://github.com/ben-eb/cssnano/releases/tag/v4.0.0-rc.0
safe: semver.satisfies(version, '<4.0.0-rc')
}
)
);
}
config.from = asset.name;
config.to = asset.name;
return config;
}