Last active
March 6, 2024 19:56
-
-
Save jandre3000/8ae4ab9251a960ac0f6c5a37bf2b4605 to your computer and use it in GitHub Desktop.
Check for undefined CSS custom properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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