npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

als-css-parser

v0.5.0

Published

Powerful CSS parser and publisher for JavaScript

Downloads

40

Readme

CSS Parser

Beta version

This module provides a simple yet powerful CSS parser for JavaScript, allowing you to easily parse, manipulate, and generate CSS stylesheets. The CssParser class accepts raw CSS code and provides a range of methods to manipulate, minify, or generate stylesheets. It also supports custom hooks to modify the behavior of the parser.

Installation

npm install als-css-parser

Usage

You can use CssParser on browser and on node.js.

Import CssParser

On node.js:

const CssParser = require('css-parser');

On browser:

<script src="node_modules/als-css-parser/css-parser.js"></script>

Create an instance of CssParser

const rawCss = 'your raw css code here';
const hooks = {}; // optional custom hooks
const cssParser = new CssParser(rawCss, hooks);

Example:

let rawCss = /*css*/`
/* Comment */
.example{
  color:red;
  display:none
}
@media screen and (max-width:600px){
  .example{
    display:block
  }
}
`
const cssParser = new CssParser(rawCss);

At this point, cssParser has rawBlocks and rawCss properties. RawCss is a rawCss parameter in constructor. ``

rawBlocks is an array with separated rule sets which looks like this:

cssParser.rawBlocks = [
    "/* Comment */",
    ".example {\n      color: red;\n      display: none;\n    }",
    "@media screen and (max-width:600px) {\n      .example {\n        display: block;\n      }}"
]

Get ruleSets

Method ruleSets return object with css tree by using hooks from constructor and options which used by hooks.

Syntax:

const options = {}; // optional ruleSets options
const ruleSets = cssParser.ruleSets(options);

The result looks like this:

ruleSets = [
    "/* Comment */",
    {
        ".example": [{"color": "red"},{"display": "none"}]
    },
    {
        "@media screen and (max-width:600px)": [
            {".example": [{"display": "block"}]}
        ]
    }
]

Generate a stylesheet

const options = {}
const stylesheet = cssParser.stylesheet(options);

By default options are:

let options = {
   space:cssParser.space, // space for formating levels
   n:cssParser.n, // new line
   nocomments:false, // don't include comments in stylesheet
   removeEmptyRulesets:true // remove empty rule sets
}

Also options may include options for hooks.

Result example:

stylesheet = 
`/* Comment */
.example{
  color:red;
  display:none
}
@media screen and (max-width:600px){
  .example{
    display:block
  }
}
`

Generate a minified stylesheet

const minifiedStylesheet = cssParser.minified(options);

The minified stylesheet add the folowing options:

options.space=''
options.n=''
options.nocomments = true

Result example:

minifiedStylesheet = 
`.example{color:red;display:none}@media screen and (max-width:600px){.example{display:block}}`

Publish

publish method creates new stylesheet or use existing one for inserting css rules to document.

cssParser.publish()

Each published rule add to CssParser.published static property and not publishing if rule allready published.

parse method

parse method creates new instance of CssParser.

const parsedRules = CssParser.parse(rawCss, hooks);

Here the code for parse method

CssParser.parse = function(rawCss,hooks) {
   return new CssParser(rawCss,hooks)
}

Hooks

Hooks can be provided when creating a new CssParser instance. Hooks are functions that get called at specific points in the parsing process and can modify the behavior of the parser. Hooks should be defined in the following format:

{
   ruleSets: {
      mainRuleSets: [],
      ruleSets: [],
      rule: []
      string: [], // may include comment, @import, @charset, @namespace
      selector: [], 
      propname: [],
      value: [],
  },
  stylesheet: {
    string: [],
    selector: [],
    propname: [],
    value: []
  }
}

hook function will get folowing parameters:

  • item value
  • args={parentSelector,selector} - selector only if needed
  • options - options from stylesheet or ruleSets
  • the instance
  • the CssParser class

Every hook has to return new value and may add event and errors to instance.events and instance.errors.

Example:

function optimizeValue(value,{parentSelector='main'},options,obj) {
   if(options.optimizeValue == false) return value
   if(value.startsWith('url') || value.startsWith('content')) return value
   value = value.replace(/\s[,)]/g,s => s.trim())
   value = value.replace(/[,(]\s/g,s => s.trim())
   value = value.replace(/0\./g,'.')
   return value
}
let options = {ruleSets:{
   value:[optimizeValue]
}}

let rawCss = `
.some {
   font-size:0.8rem;
   color: rgb(50, 50, 50);
}
`
const cssParser = new CssParser(rawCss,options);
cssParser.ruleSets()

Result

[
    {".some": [
      {"font-size": ".8rem"},
      {"color": "rgb(50,50,50)"}
   ]}
]