Search


Search something to see results

TransformOptions

Transform options

interface TransformOptions {
    arena?: AstArena;
    beautify?: boolean;
    computeCalcExpression?: boolean;
    computeShorthand?: boolean;
    computeTransform?: boolean;
    convertColor?: boolean | ColorType;
    cwd?: string;
    evaluateMixins?: boolean;
    expandIfSyntax?: boolean;
    expandNestingRules?: boolean;
    fastMode?: boolean;
    filePath?: string;
    generateScopedName?: (
        localName: string,
        filePath: string,
        pattern: string,
        hashLength?: number,
    ) => string | Promise<string>;
    hashLength?: number;
    indent?: string;
    inlineCssVariables?: boolean;
    inputSourceMap?: string | SourceMapObject;
    keepMixins?: boolean;
    lenient?: boolean;
    load?: (
        url: string | { absolute: string; relative: string },
        currentDirectory?: string,
        responseType?: boolean | ResponseType,
    ) => Promise<
        string
        | ArrayBuffer
        | ReadableStream<Uint8Array<ArrayBufferLike>>,
    >;
    mergeRules?: boolean | MergeRulesEnum;
    minify?: boolean;
    minifyAST?: boolean;
    minifyValues?: boolean;
    module?:
        | boolean
        | ModuleSyncOptions
        | ModuleCaseTransformEnum
        | ModuleScopeEnumOptions;
    naming?: ModuleCaseTransformEnum;
    nestingRules?: boolean;
    newLine?: string;
    optimizeSelectors?: boolean;
    output?: string;
    parseColor?: boolean;
    pass?: number;
    pattern?: string;
    preserveLicense?: boolean;
    removeCharset?: boolean;
    removeComments?: boolean;
    removeDuplicateDeclarations?: string
    | boolean
    | string[];
    removeEmpty?: boolean;
    removePrefix?: boolean;
    resolve?: (
        url: string,
        currentUrl: string,
        currentWorkingDirectory?: string,
    ) => { absolute: string; relative: string };
    resolveImport?: boolean;
    resolveUrls?: boolean;
    scoped?: boolean | ModuleScopeEnumOptions;
    signal?: AbortSignal;
    source?: SourceFile | null;
    sourcemap?: boolean | "inline";
    sourcesMap?: Map<number, SourceFile>;
    src?: string;
    validation?: boolean;
    visitor?:
        | GenericVisitorAstNodeSyncHandlerMap<any>
        | GenericVisitorAstNodeHandlerMap<any>
        | VisitorNodeMap
        | VisitorNodeMap[];
    withParents?: boolean;
}

Hierarchy (View Summary)

Index

Properties

node.TransformOptions.arenanode.TransformOptions.beautifynode.TransformOptions.computeCalcExpressionnode.TransformOptions.computeShorthandnode.TransformOptions.computeTransformnode.TransformOptions.convertColornode.TransformOptions.cwdnode.TransformOptions.evaluateMixinsnode.TransformOptions.expandIfSyntaxnode.TransformOptions.expandNestingRulesnode.TransformOptions.fastModenode.TransformOptions.filePathnode.TransformOptions.generateScopedNamenode.TransformOptions.hashLengthnode.TransformOptions.indentnode.TransformOptions.inlineCssVariablesnode.TransformOptions.inputSourceMapnode.TransformOptions.keepMixinsnode.TransformOptions.lenientnode.TransformOptions.loadnode.TransformOptions.mergeRulesnode.TransformOptions.minifynode.TransformOptions.minifyASTnode.TransformOptions.minifyValuesnode.TransformOptions.modulenode.TransformOptions.namingnode.TransformOptions.nestingRulesnode.TransformOptions.newLinenode.TransformOptions.optimizeSelectorsnode.TransformOptions.outputnode.TransformOptions.parseColornode.TransformOptions.passnode.TransformOptions.patternnode.TransformOptions.preserveLicensenode.TransformOptions.removeCharsetnode.TransformOptions.removeCommentsnode.TransformOptions.removeDuplicateDeclarationsnode.TransformOptions.removeEmptynode.TransformOptions.removePrefixnode.TransformOptions.resolvenode.TransformOptions.resolveImportnode.TransformOptions.resolveUrlsnode.TransformOptions.scopednode.TransformOptions.signalnode.TransformOptions.sourcenode.TransformOptions.sourcemapnode.TransformOptions.sourcesMapnode.TransformOptions.srcnode.TransformOptions.validationnode.TransformOptions.visitornode.TransformOptions.withParents
arena?: AstArena

Arena the ast nodes are allocated in. Created by the parser when omitted. Nested parses (@import) allocate their nodes in the parent arena.

beautify?: boolean

Pretty print css

const result = await transform(css, {beautify: true});
computeCalcExpression?: boolean

Compute css math functions

computeShorthand?: boolean

Compute shorthand properties

computeTransform?: boolean

Compute css transform functions

convertColor?: boolean | ColorType

Convert color to the specified color space. 'true' will convert to HEX

cwd?: string

Current working directory

evaluateMixins?: boolean

Evaluate css mixins and custom functions: the @apply rules are replaced by the body of the mixin they reference, the private variables (@private, mixin arguments and the custom properties of the rule) are substituted. the custom function calls (--fn(1px)) are replaced by the result of the function. see https://drafts.csswg.org/css-mixins-1/


import {transform} from '@tbela99/css-parser';

const css = `
@mixin --only-descs(--arg) {
color: var(--arg);
& * { color: var(--arg, red); }
}
.foo {
@apply --only-descs(green);
}
`;

const result = await transform(css, {evaluateMixins: true, expandNestingRules: true});

console.log(result.code);
// .foo,.foo *{color:green}
expandIfSyntax?: boolean

Experimental, convert css if() function into legacy syntax.

expandNestingRules?: boolean

Expand nested rules

fastMode?: boolean

Fast mode: the ast is not minified and the rules are not merged, the values are minified when they are rendered. The output is larger and the minification is faster. It sets the default value of these options, an option given explicitly takes precedence:

{
minify: false,
mergeRules: MergeRulesEnum.None,
}
import {transformSync} from '@tbela99/css-parser';

const result = transformSync(css, {fastMode: true});
filePath?: string

Module output file path. it is used to generate the scoped name. if not provided, options.src will be used

generateScopedName?: (
    localName: string,
    filePath: string,
    pattern: string,
    hashLength?: number,
) => string | Promise<string>

Function to generate scoped name

Type Declaration

    • (
          localName: string,
          filePath: string,
          pattern: string,
          hashLength?: number,
      ): string | Promise<string>
    • Parameters

      Returns string | Promise<string>

hashLength?: number

Generated scope hash length. the default is 5

indent?: string

Indention string

inlineCssVariables?: boolean

Inline css variables

inputSourceMap?: string | SourceMapObject

Input source map

keepMixins?: boolean

Keep the mixins and the custom functions once they are evaluated, see evaluateMixins. By default, the evaluated mixins and custom functions, and the mixins that are not referenced, are dropped and replaced with a comment

lenient?: boolean

Lenient validation. retain nodes that failed validation

load?: (
    url: string | { absolute: string; relative: string },
    currentDirectory?: string,
    responseType?: boolean | ResponseType,
) => Promise<
    string
    | ArrayBuffer
    | ReadableStream<Uint8Array<ArrayBufferLike>>,
>

Custom URL and file loader.

mergeRules?: boolean | MergeRulesEnum

Merge the adjacent rules (MergeRulesEnum, true is a shortcut for MergeRulesEnum.All, false for MergeRulesEnum.None).

  • MergeRulesEnum.All: the rules that share declarations are merged when the output is smaller
  • MergeRulesEnum.Identical: only the rules that have the same declarations are merged, the size of the output is not computed: .a{color:red}.b{color:red} is merged into .a,.b{color:red}
  • MergeRulesEnum.None: the rules that have different selectors are not merged

The default is MergeRulesEnum.All when the ast is minified, MergeRulesEnum.None otherwise. With minify: false, MergeRulesEnum.Identical and MergeRulesEnum.All merge the rules without minifying the ast: the adjacent rules and keyframes rules that have the same selector and the adjacent at-rules that have the same prelude are merged (@font-face is not merged), the last @keyframes of a name is kept, the rules that have different selectors are merged as above. The other minifications are not applied.

import {transformSync, MergeRulesEnum} from '@tbela99/css-parser';

// the adjacent rules that have the same declarations are merged, the ast is not minified
const result = transformSync(css, {minify: false, mergeRules: MergeRulesEnum.Identical});
minify?: boolean

Enable minification

minifyAST?: boolean

enable ast minification

minifyValues?: boolean

Minify values

module?:
    | boolean
    | ModuleSyncOptions
    | ModuleCaseTransformEnum
    | ModuleScopeEnumOptions

CSS modules options

optional. function change the case of the scoped name and the class mapping

nestingRules?: boolean

Generate nested rules

newLine?: string

New line string

optimizeSelectors?: boolean

Optimize the selectors (default true): remove the redundant selectors, factor the selectors with :is(). false only applies when nestingRules is false: the nesting of the rules reads the optimized selectors.

output?: string

Output file. Used for url resolution

parseColor?: boolean

Parse color tokens

pass?: number

Define minification passes.

pattern?: string

The pattern used to generate scoped names. the supported placeholders are:

  • name: the file base name without the extension
  • hash: the file path hash
  • local: the local name
  • path: the file path
  • folder: the folder name
  • ext: the file extension

the pattern can optionally have a maximum number of characters:

pattern: '[local:2]-[hash:5]'

the hash pattern can take an algorithm, a maximum number of characters or both:

pattern: '[local]-[hash:base64:5]'

or

pattern: '[local]-[hash:5]'

or

pattern: '[local]-[hash:sha1]'

supported hash algorithms are:

  • base64
  • hex
  • base64url
  • sha1
  • sha256
  • sha384
  • sha512

import {transform, ModuleCaseTransformEnum} from '@tbela99/css-parser';
import type {TransformResult} from '@tbela99/css-parser';
css = `
:local(.className) {
background: red;
color: yellow;
}

:local(.subClass) {
composes: className;
background: blue;
}
`;

let result: TransformResult = await transform(css, {

beautify:true,
module: {
pattern: '[local]-[hash:sha256]'
}

});

console.log(result.code);

generated css

.className-b629f {
background: red;
color: #ff0
}
.subClass-a0c35 {
background: blue
}
preserveLicense?: boolean

Preserve license comments. License comments are comments that start with '/*!'

removeCharset?: boolean

Remove at-rule charset

removeComments?: boolean

Remove comments

removeDuplicateDeclarations?: string | boolean | string[]

Remove duplicate declarations from the same rule. if passed as a string array, duplicated declarations are removed, except for those in the array


import {transform} from '@tbela99/css-parser';

const css = `

.table {

width: 100%;
width: calc(100% + 40px);
margin-left: 20px;
margin-left: min(100% , 20px)
}

`;
const result = await transform(css, {

beautify: true,
validation: true,
removeDuplicateDeclarations: ['width']
}
);

console.log(result.code);
removeEmpty?: boolean

Remove empty ast nodes

removePrefix?: boolean

Remove css prefix

resolve?: (
    url: string,
    currentUrl: string,
    currentWorkingDirectory?: string,
) => { absolute: string; relative: string }

Url and path resolver

resolveImport?: boolean

Resolve import

resolveUrls?: boolean

Resolve urls

scoped?: boolean | ModuleScopeEnumOptions

Use local scope vs global scope

signal?: AbortSignal

Abort signal

Example: abort after 10 seconds


const result = await parse(cssString, {
signal: AbortSignal.timeout(10000)
});
source?: SourceFile | null

Source file to be used for sourcemap

sourcemap?: boolean | "inline"

Include sourcemap in the ast. Sourcemap info is always generated

sourcesMap?: Map<number, SourceFile>

Source file to be used for sourcemap

src?: string

Source file to be used for sourcemap

validation?: boolean

Enable CSS validation

Node visitor VisitorNodeMap[]

withParents?: boolean

Render the node along with its parents