Skip to content

Instantly share code, notes, and snippets.

@jandre3000
Last active March 6, 2024 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jandre3000/8ae4ab9251a960ac0f6c5a37bf2b4605 to your computer and use it in GitHub Desktop.
Save jandre3000/8ae4ab9251a960ac0f6c5a37bf2b4605 to your computer and use it in GitHub Desktop.
Check for undefined CSS custom properties
/**
* Validate whether or not an undefined CSS custom property exists in a given file OR URL.
* dependencies (i.e. npm install these):
* - postcss
* - postcss-custom-properties
* - perfectionist
* - node-fetch
*/
import postcss from 'postcss';
import postcssCustomProperties from 'postcss-custom-properties';
import fetch from 'node-fetch';
import perfectionist from 'perfectionist';
import fs from 'node:fs/promises';
const CSSUrl = "https://en.m.wikipedia.org/w/load.php?lang=en&modules=codex-search-styles%7Cmobile.init.styles%7Cskins.minerva.amc.styles%7Cskins.minerva.base.styles%7Cskins.minerva.content.styles.images%7Cskins.minerva.icons.wikimedia%7Cskins.minerva.loggedin.styles%7Cskins.minerva.mainMenu.advanced.icons%7Cskins.minerva.mainMenu.icons%2Cstyles%7Cskins.minerva.mainPage.styles%7Cskins.minerva.overflow.icons%7Cskins.minerva.personalMenu.icons&only=styles&skin=minerva";
( async () => {
let inputData;
const containsVars = new RegExp(/var\(/g);
// get the CSS, either from the file, OR fetch it if the file doesn't exist.
try {
inputData = await fs.readFile('./input.css', 'utf8' );
} catch ( err ) {
inputData = await fetch( CSSUrl ).then( ( data ) => data.text() );
};
// Format it so it's readable.
const formattedInputData = await postcss( [ perfectionist() ] ).process( inputData );
// Write it to a file so we can compare the input and the output.
await fs.writeFile('input.css', formattedInputData.css, err => { if (err) { console.error(err) } } );
// Try to replace all the CSS custom properties. If this fails, then there's a problem.
const output = await postcss( [ postcssCustomProperties( { preserve: false } ) ] ).process( formattedInputData.css );
// Write all the output to a file (again, to compare with the input). There should be no var() statements in this file.
await fs.writeFile('output.css', output.css, err => { if (err) { console.error(err) } } );
// Check if any var() statements exist in the output.
if ( containsVars.test( output.css ) ) {
console.log( 'FAILURE! UH OH!' )
} else {
console.log( 'YAY! NO CSS VARS FOUND!' )
}
} )();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment