lightningcss-wasm
Advanced tools
Comparing version 1.17.1 to 1.18.0
101
index.d.ts
@@ -0,3 +1,6 @@ | ||
import type { Angle, CssColor, Rule, CustomProperty, EnvironmentVariable, Function, Image, LengthValue, MediaQuery, Declaration, Ratio, Resolution, Selector, SupportsCondition, Time, Token, TokenOrValue, UnknownAtRule, Url, Variable } from './ast'; | ||
import type { Targets } from './targets'; | ||
export * from './ast'; | ||
export interface TransformOptions { | ||
@@ -14,2 +17,7 @@ /** The filename being transformed. Used for error messages and source maps. */ | ||
inputSourceMap?: string, | ||
/** | ||
* An optional project root path, used as the source root in the output source map. | ||
* Also used to generate relative paths for sources used in CSS module hashes. | ||
*/ | ||
projectRoot?: string, | ||
/** The browser targets for the generated code. */ | ||
@@ -44,5 +52,82 @@ targets?: Targets, | ||
*/ | ||
errorRecovery?: boolean | ||
errorRecovery?: boolean, | ||
/** | ||
* An AST visitor object. This allows custom transforms or analysis to be implemented in JavaScript. | ||
* Multiple visitors can be composed into one using the `composeVisitors` function. | ||
* For optimal performance, visitors should be as specific as possible about what types of values | ||
* they care about so that JavaScript has to be called as little as possible. | ||
*/ | ||
visitor?: Visitor | ||
} | ||
type FindByType<Union, Name> = Union extends { type: Name } ? Union : never; | ||
type RuleVisitor<R = Rule> = ((rule: R) => Rule | Rule[] | void); | ||
type MappedRuleVisitors = { | ||
[Name in Exclude<Rule['type'], 'unknown' | 'custom'>]?: RuleVisitor<FindByType<Rule, Name>>; | ||
} | ||
type UnknownVisitors = { | ||
[name: string]: RuleVisitor<UnknownAtRule> | ||
} | ||
type RuleVisitors = MappedRuleVisitors & { | ||
unknown?: UnknownVisitors | RuleVisitor<UnknownAtRule> | ||
}; | ||
type FindProperty<Union, Name> = Union extends { property: Name } ? Union : never; | ||
type DeclarationVisitor<P = Declaration> = ((property: P) => Declaration | Declaration[] | void); | ||
type MappedDeclarationVisitors = { | ||
[Name in Exclude<Declaration['property'], 'unparsed' | 'custom'>]?: DeclarationVisitor<FindProperty<Declaration, Name> | FindProperty<Declaration, 'unparsed'>>; | ||
} | ||
type CustomPropertyVisitors = { | ||
[name: string]: DeclarationVisitor<CustomProperty> | ||
} | ||
type DeclarationVisitors = MappedDeclarationVisitors & { | ||
custom?: CustomPropertyVisitors | DeclarationVisitor<CustomProperty> | ||
} | ||
type TokenVisitor = (token: Token) => TokenOrValue | TokenOrValue[] | void; | ||
type VisitableTokenTypes = 'ident' | 'at-keyword' | 'hash' | 'id-hash' | 'string' | 'number' | 'percentage' | 'dimension'; | ||
type TokenVisitors = { | ||
[Name in VisitableTokenTypes]?: (token: FindByType<Token, Name>) => TokenOrValue | TokenOrValue[] | void; | ||
} | ||
type FunctionVisitor = (fn: Function) => TokenOrValue | TokenOrValue[] | void; | ||
type EnvironmentVariableVisitor = (env: EnvironmentVariable) => TokenOrValue | TokenOrValue[] | void; | ||
type EnvironmentVariableVisitors = { | ||
[name: string]: EnvironmentVariableVisitor | ||
}; | ||
export interface Visitor { | ||
Rule?: RuleVisitor | RuleVisitors; | ||
RuleExit?: RuleVisitor | RuleVisitors; | ||
Declaration?: DeclarationVisitor | DeclarationVisitors; | ||
DeclarationExit?: DeclarationVisitor | DeclarationVisitors; | ||
Url?(url: Url): Url | void; | ||
Color?(color: CssColor): CssColor | void; | ||
Image?(image: Image): Image | void; | ||
ImageExit?(image: Image): Image | void; | ||
Length?(length: LengthValue): LengthValue | void; | ||
Angle?(angle: Angle): Angle | void; | ||
Ratio?(ratio: Ratio): Ratio | void; | ||
Resolution?(resolution: Resolution): Resolution | void; | ||
Time?(time: Time): Time | void; | ||
CustomIdent?(ident: string): string | void; | ||
DashedIdent?(ident: string): string | void; | ||
MediaQuery?(query: MediaQuery): MediaQuery | MediaQuery[] | void; | ||
MediaQueryExit?(query: MediaQuery): MediaQuery | MediaQuery[] | void; | ||
SupportsCondition?(condition: SupportsCondition): SupportsCondition; | ||
SupportsConditionExit?(condition: SupportsCondition): SupportsCondition; | ||
Selector?(selector: Selector): Selector | Selector[] | void; | ||
Token?: TokenVisitor | TokenVisitors; | ||
Function?: FunctionVisitor | { [name: string]: FunctionVisitor }; | ||
FunctionExit?: FunctionVisitor | { [name: string]: FunctionVisitor }; | ||
Variable?(variable: Variable): TokenOrValue | TokenOrValue[] | void; | ||
VariableExit?(variable: Variable): TokenOrValue | TokenOrValue[] | void; | ||
EnvironmentVariable?: EnvironmentVariableVisitor | EnvironmentVariableVisitors; | ||
EnvironmentVariableExit?: EnvironmentVariableVisitor | EnvironmentVariableVisitors; | ||
} | ||
export interface DependencyOptions { | ||
@@ -227,3 +312,10 @@ /** Whether to preserve `@import` rules rather than removing them. */ | ||
*/ | ||
errorRecovery?: boolean | ||
errorRecovery?: boolean, | ||
/** | ||
* An AST visitor object. This allows custom transforms or analysis to be implemented in JavaScript. | ||
* Multiple visitors can be composed into one using the `composeVisitors` function. | ||
* For optimal performance, visitors should be as specific as possible about what types of values | ||
* they care about so that JavaScript has to be called as little as possible. | ||
*/ | ||
visitor?: Visitor | ||
} | ||
@@ -261,3 +353,8 @@ | ||
/** | ||
* Composes multiple visitor objects into a single one. | ||
*/ | ||
export declare function composeVisitors(visitors: Visitor[]): Visitor; | ||
/** Initializes the web assembly module. */ | ||
export default function init(input?: string | URL | Request): Promise<void>; |
{ | ||
"name": "lightningcss-wasm", | ||
"version": "1.17.1", | ||
"version": "1.18.0", | ||
"license": "MPL-2.0", | ||
"description": "A CSS parser, transformer, and minifier written in Rust", | ||
"main": "index.js", | ||
"main": "index.mjs", | ||
"types": "index.d.ts", | ||
@@ -23,5 +23,18 @@ "browserslist": "last 2 versions, not dead", | ||
}, | ||
"files": [ | ||
"*.js", | ||
"*.mjs", | ||
"*.d.ts", | ||
"*.flow", | ||
"*.wasm" | ||
], | ||
"dependencies": { | ||
"napi-wasm": "^1.0.1" | ||
}, | ||
"resolutions": { | ||
"lightningcss": "link:." | ||
}, | ||
"type": "module", | ||
"module": "index.js", | ||
"module": "index.mjs", | ||
"sideEffects": false | ||
} |
185
README.md
@@ -1,2 +0,2 @@ | ||
# ⚡️ Lightning CSS | ||
# ⚡️ lightningcss-wasm | ||
@@ -60,187 +60,8 @@ An extremely fast CSS parser, transformer, and minifier written in Rust. Use it with [Parcel](https://parceljs.org), as a standalone library or CLI, or via a plugin with any other tool. | ||
- The `composes` property | ||
- **Custom transforms** – The Lightning CSS visitor API can be used to implement custom transform plugins. | ||
## Documentation | ||
Lightning CSS can be used from [Parcel](https://parceljs.org), as a standalone library from JavaScript or Rust, using a standalone CLI, or wrapped as a plugin within any other tool. | ||
Lightning CSS can be used from [Parcel](https://parceljs.org), as a standalone library from JavaScript or Rust, using a standalone CLI, or wrapped as a plugin within any other tool. See the [Lightning CSS website](https://lightningcss.dev/docs.html) for documentation. | ||
### From Node | ||
See the [TypeScript definitions](https://github.com/parcel-bundler/lightningcss/blob/master/node/index.d.ts) for full API docs. | ||
Here is a simple example that compiles the input CSS for Safari 13.2, and minifies the output. | ||
```js | ||
const css = require('lightningcss'); | ||
let {code, map} = css.transform({ | ||
filename: 'style.css', | ||
code: Buffer.from('.foo { color: red }'), | ||
minify: true, | ||
sourceMap: true, | ||
targets: { | ||
// Semver versions are represented using a single 24-bit number, with one component per byte. | ||
// e.g. to represent 13.2.0, the following could be used. | ||
safari: (13 << 16) | (2 << 8) | ||
} | ||
}); | ||
``` | ||
You can also convert the results of running `browserslist` into targets which can be passed to Lightning CSS: | ||
```js | ||
const browserslist = require('browserslist'); | ||
const css = require('lightningcss'); | ||
let targets = css.browserslistToTargets(browserslist('>= 0.25%')); | ||
``` | ||
Bundling is also possible by using the `bundle` API. This processes `@import` rules and inlines them. This API requires filesystem access, so it does not accept `code` directly via the API. | ||
```js | ||
let {code, map} = css.bundle({ | ||
filename: 'style.css', | ||
minify: true | ||
}); | ||
``` | ||
The `bundleAsync` API is an asynchronous version of `bundle`, which also accepts a custom `resolver` object. This allows you to provide custom JavaScript functions for resolving `@import` specifiers to file paths, and reading files from the file system (or another source). The `read` and `resolve` functions are both optional, and may either return a string synchronously, or a Promise for asynchronous resolution. | ||
```js | ||
let {code, map} = await css.bundleAsync({ | ||
filename: 'style.css', | ||
minify: true, | ||
resolver: { | ||
read(filePath) { | ||
return fs.readFileSync(filePath, 'utf8'); | ||
}, | ||
resolve(specifier, from) { | ||
return path.resolve(path.dirname(from), specifier); | ||
} | ||
} | ||
}); | ||
``` | ||
Note that using a custom resolver can slow down bundling significantly, especially when reading files asynchronously. Use `readFileSync` rather than `readFile` if possible for better performance, or omit either of the methods if you don't need to override the default behavior. | ||
### From Rust | ||
See the Rust API docs on [docs.rs](https://docs.rs/lightningcss). | ||
### With Parcel | ||
Parcel includes Lightning CSS as the default CSS transformer. You should also add a `browserslist` property to your `package.json`, which defines the target browsers that your CSS will be compiled for. | ||
While Lightning CSS handles the most commonly used PostCSS plugins like `autoprefixer`, `postcss-preset-env`, and CSS modules, you may still need PostCSS for more custom plugins like TailwindCSS. If that's the case, your PostCSS config will be picked up automatically. You can remove the plugins listed above from your PostCSS config, and they'll be handled by Lightning CSS. | ||
You can also configure Lightning CSS in the `package.json` in the root of your project. Currently, three options are supported: `drafts`, which can be used to enable CSS nesting and custom media queries, `pseudoClasses`, which allows replacing some pseudo classes like `:focus-visible` with normal classes that can be applied via JavaScript (e.g. polyfills), and `cssModules`, which enables CSS modules globally rather than only for files ending in `.module.css`, or accepts an options object. | ||
```json | ||
{ | ||
"@parcel/transformer-css": { | ||
"cssModules": true, | ||
"drafts": { | ||
"nesting": true, | ||
"customMedia": true | ||
}, | ||
"pseudoClasses": { | ||
"focusVisible": "focus-ring" | ||
} | ||
} | ||
} | ||
``` | ||
See the [Parcel docs](https://parceljs.org/languages/css) for more details. | ||
### From Deno or in browser | ||
The `lightningcss-wasm` package can be used in Deno or directly in browsers. This uses a WebAssembly build of Lightning CSS. Use `TextEncoder` and `TextDecoder` convert code from a string to a typed array and back. | ||
```js | ||
import init, {transform} from 'https://unpkg.com/lightningcss-wasm'; | ||
await init(); | ||
let {code, map} = transform({ | ||
filename: 'style.css', | ||
code: new TextEncoder().encode('.foo { color: red }'), | ||
minify: true, | ||
}); | ||
console.log(new TextDecoder().decode(code)); | ||
``` | ||
### With webpack | ||
css-minimizer-webpack-plugin has builtin support for Lightning CSS. Install Lightning CSS in your project, and configure the plugin as documented [in its README](https://github.com/webpack-contrib/css-minimizer-webpack-plugin#using-custom-minifier-lightningcss-previously-parcelcss). | ||
### From the CLI | ||
Lightning CSS includes a standalone CLI that can be used to compile, minify, and bundle CSS files. It can be used when you only need to compile CSS, and don't need more advanced functionality from a larger build tool such as code splitting and support for other languages. | ||
To use the CLI, install the `lightningcss-cli` package with an npm compatible package manager: | ||
```shell | ||
npm install lightningcss-cli | ||
``` | ||
Then, you can run the `lightningcss` command via `npx`, `yarn`, or by setting up a script in your package.json. | ||
```json | ||
{ | ||
"scripts": { | ||
"build": "lightningcss --minify --nesting --bundle --targets '>= 0.25%' --sourcemap input.css -o output.css" | ||
} | ||
} | ||
``` | ||
To see all of the available options, use the `--help` argument: | ||
```shell | ||
npx lightningcss --help | ||
``` | ||
#### Browserslist configuration | ||
If the `--browserslist` option is provided, then `lightningcss` finds browserslist configuration, | ||
selects queries by environment and loads the resulting queries as targets. | ||
Configuration discovery and targets resolution is modeled after the original `browserslist` nodeJS package. | ||
The configuration is resolved in the following order: | ||
- If a `BROWSERSLIST` environment variable is present, then load targets from its value. This is analog to the `--targets` CLI option. | ||
_Example:_ `BROWSERSLIST="firefox ESR" lightningcss [OPTIONS] <INPUT_FILE>` | ||
- If a `BROWSERSLIST_CONFIG` environment variable is present, then resolve the file at the provided path. | ||
Then parse and use targets from `package.json` or any browserslist configuration file pointed to by the environment variable. | ||
_Example:_ `BROWSERSLIST_CONFIG="../config/browserslist" lightningcss [OPTIONS] <INPUT_FILE>` | ||
- If none of the above apply, then find, parse and use targets from the first `browserslist`, `.browserslistrc` | ||
or `package.json` configuration file in any parent directory. | ||
Browserslist configuration files may contain sections denoted by angular brackets `[]`. | ||
Use these to specify different targets for different environments. | ||
Targets which are not placed in a section are added to `defaults` and used if no section matches the environment. | ||
_Example:_ | ||
``` | ||
# Defaults, applied when no other section matches the provided environment. | ||
firefox ESR | ||
[staging] | ||
# Targets applied only to the staging environment. | ||
samsung >= 4 | ||
``` | ||
When using parsed configuration from `browserslist`, `.browserslistrc` or `package.json` configuration files, | ||
the environment determined by | ||
- the `BROWSERSLIST_ENV` environment variable if present, | ||
- otherwise the `NODE_ENV` environment variable if present, | ||
- otherwise `production` is used. | ||
If no targets are found for the resulting environment, then the `defaults` configuration section is used. | ||
### Error recovery | ||
By default, Lightning CSS is strict, and will error when parsing an invalid rule or declaration. However, sometimes you may encounter a third party library that you can't easily modify, which unintentionally contains invalid syntax, or IE-specific hacks. In these cases, you can enable the `errorRecovery` option (or `--error-recovery` CLI flag). This will skip over invalid rules and declarations, omitting them in the output, and producing a warning instead of an error. You should also open an issue or PR to fix the issue in the library if possible. | ||
## Benchmarks | ||
@@ -247,0 +68,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Native code
Supply chain riskContains native code (e.g., compiled binaries or shared libraries). Including native code can obscure malicious behavior.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Native code
Supply chain riskContains native code (e.g., compiled binaries or shared libraries). Including native code can obscure malicious behavior.
Found 1 instance in 1 package
8792660
9273
1
8
106
3
+ Addednapi-wasm@^1.0.1
+ Addednapi-wasm@1.1.3(transitive)