What is postcss-syntax?
The postcss-syntax npm package is a syntax parser for PostCSS that allows you to parse and stringify CSS, LESS, SCSS, and other syntaxes in a unified way. It enables PostCSS to understand these various syntaxes, which can be useful for tasks such as linting, minification, and applying other PostCSS plugins to non-standard CSS files.
What are postcss-syntax's main functionalities?
Parsing CSS-like syntaxes
This feature allows you to use PostCSS to parse different CSS-like syntaxes such as SCSS or LESS. The code sample demonstrates how to process a source string with PostCSS using the postcss-syntax package to handle different syntaxes.
const postcss = require('postcss');
const syntax = require('postcss-syntax');
postcss(plugins).process(source, { syntax: syntax }).then(result => {
console.log(result.content);
});
Stringifying parsed syntaxes
After parsing CSS-like syntaxes, postcss-syntax can also be used to stringify the parsed abstract syntax tree (AST) back into a CSS string. This is useful for transforming code and then outputting the result.
const postcss = require('postcss');
const syntax = require('postcss-syntax');
const root = postcss.parse(source, { syntax: syntax });
const css = root.toString(syntax);
Other packages similar to postcss-syntax
postcss-scss
This package is a SCSS parser for PostCSS. It allows you to work with SCSS syntax specifically, whereas postcss-syntax is more general and can handle multiple syntaxes.
postcss-less
Similar to postcss-scss, postcss-less is a parser that allows PostCSS to understand LESS syntax. It is specifically tailored for LESS, unlike postcss-syntax which is more versatile.
sugarss
SugarSS is an indented syntax parser for PostCSS. It is a more specialized tool compared to postcss-syntax, focusing on a syntax that is similar to Sass or Stylus but with a different set of features.
PostCSS Syntax
postcss-syntax can automatically switch the required PostCSS syntax by file extension/source
Getting Started
First thing's first, install the module:
npm install postcss-syntax --save-dev
If you want support SCSS/SASS/LESS/SugarSS syntax, you need to install these module:
If you want support HTML (and HTML-like)/Markdown/CSS-in-JS file format, you need to install these module:
Use Cases
const postcss = require('postcss');
const syntax = require('postcss-syntax')({
rules: [
{
test: /\.(?:[sx]?html?|[sx]ht|vue|ux|php)$/i,
extract: 'html',
},
{
test: /\.(?:markdown|md)$/i,
extract: 'markdown',
},
{
test: /\.(?:m?[jt]sx?|es\d*|pac)$/i,
extract: 'jsx',
},
{
test: /\.postcss$/i,
lang: 'scss'
},
{
test: /\.customcss$/i,
lang: 'custom'
},
],
css: 'postcss-safe-parser',
sass: require('postcss-sass'),
scss: 'postcss-scss',
less: './node_modules/postcss-less',
sugarss: require('sugarss'),
custom: require('postcss-custom-syntax'),
});
postcss(plugins).process(source, { syntax: syntax }).then(function (result) {
result.content
});