index.js
1.33 KB
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
'use strict';
const charset = 'charset';
// eslint-disable-next-line no-control-regex
const nonAscii = /[^\x00-\x7F]/;
/**
* @typedef {{add?: boolean}} Options
*/
/**
* @type {import('postcss').PluginCreator<Options>}
* @param {Options} opts
* @return {import('postcss').Plugin}
*/
function pluginCreator(opts = {}) {
return {
postcssPlugin: 'postcss-normalize-' + charset,
OnceExit(css, { AtRule }) {
/** @type {import('postcss').AtRule | undefined} */
let charsetRule;
/** @type {import('postcss').Node | undefined} */
let nonAsciiNode;
css.walk((node) => {
if (node.type === 'atrule' && node.name === charset) {
if (!charsetRule) {
charsetRule = node;
}
node.remove();
} else if (
!nonAsciiNode &&
node.parent === css &&
nonAscii.test(node.toString())
) {
nonAsciiNode = node;
}
});
if (nonAsciiNode) {
if (!charsetRule && opts.add !== false) {
charsetRule = new AtRule({
name: charset,
params: '"utf-8"',
});
}
if (charsetRule) {
charsetRule.source = nonAsciiNode.source;
css.prepend(charsetRule);
}
}
},
};
}
pluginCreator.postcss = true;
module.exports = pluginCreator;