UNPKG

postcss-normalize-charset

Version:

Add necessary or remove extra charset with PostCSS

70 lines (64 loc) 1.85 kB
const charset = 'charset'; // eslint-disable-next-line no-control-regex const nonAscii = /[^\x00-\x7F]/; /** * @typedef {{add?: boolean}} Options */ /** * @param {Options} opts * @return {import('postcss').Plugin} */ function pluginCreator(opts = {}) { return { postcssPlugin: 'postcss-normalize-' + charset, /** * @param {import('postcss').Root} css * @param {import('postcss').Helpers} helpers */ OnceExit(css, { AtRule }) { /** @type {import('postcss').AtRule | undefined} */ let charsetRule; /** @type {import('postcss').Node | undefined} */ let nonAsciiNode; /** @type {string | undefined} */ let charsetSeparator; css.walk((node) => { if (node.type === 'atrule' && node.name === charset) { if (!charsetRule) { charsetRule = node; if (node === css.first) { charsetSeparator = node.next()?.raws.before; } } 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); const nextNode = charsetRule.next(); if (charsetSeparator !== undefined && nextNode) { nextNode.raws.before = charsetSeparator; } } } }, }; } /** @type {true} */ pluginCreator.postcss = true; const moduleExports = pluginCreator; export { moduleExports as default, moduleExports as 'module.exports' };