Added logging, changed some directory structure

This commit is contained in:
2018-01-13 21:33:40 -05:00
parent f079a5f067
commit 8e72ffb917
73656 changed files with 35284 additions and 53718 deletions

View File

@@ -0,0 +1,523 @@
# Change Log
This project adheres to [Semantic Versioning](http://semver.org/).
## 6.0.14
* Fix TypeScript definitions (by Jed Mao).
## 6.0.13
* Fix TypeScript definitions for case of multiple PostCSS versions
in `node_modules` (by Chris Eppstein).
* Use `source-map` 0.6.
## 6.0.12
* Dont copy `*` hack to declaration indent.
## 6.0.11
* Add upper case `!IMPORTANT` support.
## 6.0.10
* Reduce PostCSS size in webpack bundle.
## 6.0.9
* Improve error message for plugin with old PostCSS (by Igor Adamenko).
## 6.0.8
* Fix Node.js 4.2.2 support.
## 6.0.7
* Fix base64 decoding for old Node.js and browser.
## 6.0.6
* Fix `end` position in at-rule without semicolon (by Oleh Kuchuk).
## 6.0.5
* Move Babel config from `package.json` for `node_modules` compiling cases.
## 6.0.4
* Fix parsing `;;` after rules.
* Use Chalk 2.0.
## 6.0.3
* Fix escape sequences parsing (by Oleh Kuchuk).
* Added ability to force disable colors with an environment variable.
* Improved color detection of some terminal apps.
## 6.0.2
* Keep `raws.before` on moving `Root` children to new `Root`.
## 6.0.1
* Fix parser extensibility to use it in Safe Parser.
## 6.0 “Marquis Orias”
* Remove node.js 0.12 support.
* Remove deprecated method from PostCSS 4.
* Insert methods remove child from previous parent, instead of closing.
* Insert methods and cloning doesnt clean `raws` anymore.
* Methods `moveTo`, `moveAfter`, `moveBefore` were deprecated.
* Options was changed in `Plugin#process(css, processOptions, pluginOptions)`.
* Add stream parser to reduce memory usage (by Oleh Kuchuk).
* Add `before()`/`after()` shortcuts for `node.parent.insertBefore(node, x)`.
* Add `Rule#raws.ownSemicolon` for semicolon after templates for `@apply`.
* Use `babel-preset-env` to compile npm package.
* Remove `js-base64` from dependencies (by Roman Dvornov).
* Fix error message on single `:` in CSS.
* Move tests to Jest.
* Clean up test (by Gabriel Kalani).
## 5.2.18
* Fix TypeScript definitions for case of multiple PostCSS versions
in `node_modules` (by Chris Eppstein).
## 5.2.17
* Add `postcss-sass` suggestion to syntax error on `.sass` input.
## 5.2.16
* Better error on wrong argument in node constructor.
## 5.2.15
* Fix TypeScript definitions (by bumbleblym).
## 5.2.14
* Fix browser bundle building in webpack (by janschoenherr).
## 5.2.13
* Do not add comment to important raws.
* Fix JSDoc (by Dmitry Semigradsky).
## 5.2.12
* Fix typo in deprecation message (by Garet McKinley).
## 5.2.11
* Fix TypeScript definitions (by Jed Mao).
## 5.2.10
* Fix TypeScript definitions (by Jed Mao).
## 5.2.9
* Update TypeScript definitions (by Jed Mao).
## 5.2.8
* Fix error message (by Ben Briggs).
## 5.2.7
* Better error message on syntax object in plugins list.
## 5.2.6
* Fix `postcss.vendor` for values with spaces (by 刘祺).
## 5.2.5
* Better error message on unclosed string (by Ben Briggs).
## 5.2.4
* Improve terminal CSS syntax highlight (by Simon Lydell).
## 5.2.3
* Better color highlight in syntax error code frame.
* Fix color highlight support in old systems.
## 5.2.2
* Update `Processor#version`.
## 5.2.1
* Fix source map path for CSS without `from` option (by Michele Locati).
## 5.2 “Duke Vapula”
* Add syntax highlight to code frame in syntax error (by Andrey Popp).
* Use Babel code frame style and size in syntax error.
* Add `[` and `]` tokens to parse `[attr=;] {}` correctly.
* Add `ignoreErrors` options to tokenizer (by Andrey Popp).
* Fix error position on tab indent (by Simon Lydell).
## 5.1.2
* Suggests SCSS/Less parsers on parse errors depends on file extension.
## 5.1.1
* Fix TypeScript definitions (by Efremov Alexey).
## 5.1 “King and President Zagan”
* Add URI in source map support (by Mark Finger).
* Add `map.from` option (by Mark Finger).
* Add `<no source>` mappings for nodes without source (by Bogdan Chadkin).
* Add function value support to `map.prev` option (by Chris Montoro).
* Add declaration value type check in shortcut creating (by 刘祺).
* `Result#warn` now returns new created warning.
* Dont call plugin creator in `postcss.plugin` call.
* Add source maps to PostCSS ES5 build.
* Add JSDoc to PostCSS classes.
* Clean npm package from unnecessary docs.
## 5.0.21
* Fix support with input source mao with `utf8` encoding name.
## 5.0.20
* Fix between raw value parsing (by David Clark).
* Update TypeScript definitions (by Jed Mao).
* Clean fake node.source after `append(string)`.
## 5.0.19
* Fix indent-based syntaxes support.
## 5.0.18
* Parse new lines according W3C CSS syntax specification.
## 5.0.17
* Fix options argument in `Node#warn` (by Ben Briggs).
* Fix TypeScript definitions (by Jed Mao).
## 5.0.16
* Fix CSS syntax error position on unclosed quotes.
## 5.0.15
* Fix `Node#clone()` on `null` value somewhere in node.
## 5.0.14
* Allow to use PostCSS in webpack bundle without JSON loader.
## 5.0.13
* Fix `index` and `word` options in `Warning#toString` (by Bogdan Chadkin).
* Fix input source content loading in errors.
* Fix map options on using `LazyResult` as input CSS.
* 100% test coverage.
* Use Babel 6.
## 5.0.12
* Allow passing a previous map with no mappings (by Andreas Lind).
## 5.0.11
* Increase plugins performance by 1.5 times.
## 5.0.10
* Fix warning from nodes without source.
## 5.0.9
* Fix source map type detection (by @asan).
## 5.0.8
* Fixed a missed step in `5.0.7` that caused the module to be published as
ES6 code.
## 5.0.7
* PostCSS now requires that node 0.12 is installed via the engines property
in package.json (by Howard Zuo).
## 5.0.6
* Fix parsing nested at-rule without semicolon (by Matt Drake).
* Trim `Declaration#value` (by Bogdan Chadkin).
## 5.0.5
* Fix multi-tokens property parsing (by Matt Drake).
## 5.0.4
* Fix start position in `Root#source`.
* Fix source map annotation, when CSS uses `\r\n` (by Mohammad Younes).
## 5.0.3
* Fix `url()` parsing.
* Fix using `selectors` in `Rule` constructor.
* Add start source to `Root` node.
## 5.0.2
* Fix `remove(index)` to be compatible with 4.x plugin.
## 5.0.1
* Fix PostCSS 4.x plugins compatibility.
* Fix type definition loading (by Jed Mao).
## 5.0 “President Valac”
* Remove `safe` option. Move Safe Parser to separate project.
* `Node#toString` does not include `before` for root nodes.
* Remove plugin returning `Root` API.
* Remove Promise polyfill for node.js 0.10.
* Deprecate `eachInside`, `eachDecl`, `eachRule`, `eachAtRule` and `eachComment`
in favor of `walk`, `walkDecls`, `walkRules`, `walkAtRules` and `walkComments`
(by Jed Mao).
* Deprecate `Container#remove` and `Node#removeSelf`
in favor of `Container#removeChild` and `Node#remove` (by Ben Briggs).
* Deprecate `Node#replace` in favor of `replaceWith` (by Ben Briggs).
* Deprecate raw properties in favor of `Node#raws` object.
* Deprecate `Node#style` in favor of `raw`.
* Deprecate `CssSyntaxError#generated` in favor of `input`.
* Deprecate `Node#cleanStyles` in favor of `cleanRaws`.
* Deprecate `Root#prevMap` in favor of `Root.source.input.map`.
* Add `syntax`, `parser` and `stringifier` options for Custom Syntaxes.
* Add stringifier option to `Node#toString`.
* Add `Result#content` alias for non-CSS syntaxes.
* Add `plugin.process(css)` shortcut to every plugin function (by Ben Briggs).
* Add multiple nodes support to insert methods (by Jonathan Neal).
* Add `Node#warn` shortcut (by Ben Briggs).
* Add `word` and `index` options to errors and warnings (by David Clark).
* Add `line`, `column` properties to `Warning`.
* Use `supports-color` library to detect color support in error output.
* Add type definitions for TypeScript plugin developers (by Jed Mao).
* `Rule#selectors` setter detects separators.
* Add `postcss.stringify` method.
* Throw descriptive errors for incorrectly formatted plugins.
* Add docs to npm release.
* Fix `url()` parsing.
* Fix Windows support (by Jed Mao).
## 4.1.16
* Fix errors without stack trace.
## 4.1.15
* Allow asynchronous plugins to change processor plugins list (by Ben Briggs).
## 4.1.14
* Fix for plugins packs defined by `postcss.plugin`.
## 4.1.13
* Fix input inlined source maps with UTF-8 encoding.
## 4.1.12
* Update Promise polyfill.
## 4.1.11
* Fix error message on wrong plugin format.
## 4.1.10
* Fix Promise behavior on sync plugin errors.
* Automatically fill `plugin` field in `CssSyntaxError`.
* Fix warning message (by Ben Briggs).
## 4.1.9
* Speed up `node.clone()`.
## 4.1.8
* Accepts `Processor` instance in `postcss()` constructor too.
## 4.1.7
* Speed up `postcss.list` (by Bogdan Chadkin).
## 4.1.6
* Fix Promise behavior on parsing error.
## 4.1.5
* Parse at-words in declaration values.
## 4.1.4
* Fix Promise polyfill dependency (by Anton Yakushev and Matija Marohnić).
## 4.1.3
* Add Promise polyfill for node.js 0.10 and IE.
## 4.1.2
* List helpers can be accessed independently `var space = postcss.list.space`.
## 4.1.1
* Show deprecated message only once.
## 4.1 “Marquis Andras”
* Asynchronous plugin support.
* Add warnings from plugins and `Result#messages`.
* Add `postcss.plugin()` to create plugins with a standard API.
* Insert nodes by CSS string.
* Show version warning message on error from an outdated plugin.
* Send `Result` instance to plugins as the second argument.
* Add `CssSyntaxError#plugin`.
* Add `CssSyntaxError#showSourceCode()`.
* Add `postcss.list` and `postcss.vendor` aliases.
* Add `Processor#version`.
* Parse wrong closing bracket.
* Parse `!important` statement with spaces and comments inside (by Ben Briggs).
* Throw an error on declaration without `prop` or `value` (by Philip Peterson).
* Fix source map mappings position.
* Add indexed source map support.
* Always set `error.generated`.
* Clean all source map annotation comments.
## 4.0.6
* Remove `babel` from released package dependencies (by Andres Suarez).
## 4.0.5
* Fix error message on double colon in declaration.
## 4.0.4
* Fix indent detection in some rare cases.
## 4.0.3
* Faster API with 6to5 Loose mode.
* Fix indexed source maps support.
## 4.0.2
* Do not copy IE hacks to code style.
## 4.0.1
* Add `source.input` to `Root` too.
## 4.0 “Duke Flauros”
* Rename `Container#childs` to `nodes`.
* Rename `PostCSS#processors` to `plugins`.
* Add `Node#replaceValues()` method.
* Add `Node#moveTo()`, `moveBefore()` and `moveAfter()` methods.
* Add `Node#cloneBefore()` and `cloneAfter()` shortcuts.
* Add `Node#next()`, `prev()` and `root()` shortcuts.
* Add `Node#replaceWith()` method.
* Add `Node#error()` method.
* Add `Container#removeAll()` method.
* Add filter argument to `eachDecl()` and `eachAtRule()`.
* Add `Node#source.input` and move `source.file` or `source.id` to `input`.
* Change code indent, when node was moved.
* Better fix code style on `Rule`, `AtRule` and `Comment` nodes changes.
* Allow to create rules and at-rules by hash shortcut in append methods.
* Add class name to CSS syntax error output.
## 3.0.7
* Fix IE filter parsing with multiple commands.
* Safer way to consume PostCSS object as plugin (by Maxime Thirouin).
## 3.0.6
* Fix missing semicolon when comment comes after last declaration.
* Fix Safe Mode declaration parsing on unclosed blocks.
## 3.0.5
* Fix parser to support difficult cases with backslash escape and brackets.
* Add `CssSyntaxError#stack` (by Maxime Thirouin).
## 3.0.4
* Fix Safe Mode on unknown word before declaration.
## 3.0.3
* Increase tokenizer speed (by Roman Dvornov).
## 3.0.2
* Fix empty comment parsing.
* Fix `Root#normalize` in some inserts.
## 3.0.1
* Fix Rhino JS runtime support.
* Typo in deprecated warning (by Maxime Thirouin).
## 3.0 “Marquis Andrealphus”
* New parser, which become the fastest ever CSS parser written in JavaScript.
* Parser can now parse declarations and rules in one parent (like in `@page`)
and nested declarations for plugins like `postcss-nested`.
* Child nodes array is now in `childs` property, instead of `decls` and `rules`.
* `map.inline` and `map.sourcesContent` options are now `true` by default.
* Fix iterators (`each`, `insertAfter`) on children array changes.
* Use previous source map to show origin source of CSS syntax error.
* Use 6to5 ES6 compiler, instead of ES6 Transpiler.
* Use code style for manually added rules from existing rules.
* Use `from` option from previous source map `file` field.
* Set `to` value to `from` if `to` option is missing.
* Use better node source name when missing `from` option.
* Show a syntax error when `;` is missed between declarations.
* Allow to pass `PostCSS` instance or list of plugins to `use()` method.
* Allow to pass `Result` instance to `process()` method.
* Trim Unicode BOM on source maps parsing.
* Parse at-rules without spaces like `@import"file"`.
* Better previous `sourceMappingURL` annotation comment cleaning.
* Do not remove previous `sourceMappingURL` comment on `map.annotation: false`.
* Parse nameless at-rules in Safe Mode.
* Fix source map generation for nodes without source.
* Fix next child `before` if `Root` first child got removed.
## 2.2.6
* Fix map generation for nodes without source (by Josiah Savary).
## 2.2.5
* Fix source map with BOM marker support (by Mohammad Younes).
* Fix source map paths (by Mohammad Younes).
## 2.2.4
* Fix `prepend()` on empty `Root`.
## 2.2.3
* Allow to use object shortcut in `use()` with functions like `autoprefixer`.
## 2.2.2
* Add shortcut to set processors in `use()` via object with `.postcss` property.
## 2.2.1
* Send `opts` from `Processor#process(css, opts)` to processors.
## 2.2 “Marquis Cimeies”
* Use GNU style syntax error messages.
* Add `Node#replace` method.
* Add `CssSyntaxError#reason` property.
## 2.1.2
* Fix UTF-8 support in inline source map.
* Fix source map `sourcesContent` if there is no `from` and `to` options.
## 2.1.1
* Allow to miss `to` and `from` options for inline source maps.
* Add `Node#source.id` if file name is unknown.
* Better detect splitter between rules in CSS concatenation tools.
* Automatically clone node in insert methods.
## 2.1 “King Amdusias”
* Change Traceur ES6 compiler to ES6 Transpiler.
* Show broken CSS line in syntax error.
## 2.0 “King Belial”
* Project was rewritten from CoffeeScript to ES6.
* Add Safe Mode to works with live input or with hacks from legacy code.
* More safer parser to pass all hacks from Browserhacks.com.
* Use real properties instead of magic getter/setter for raw properties.
## 1.0 “Marquis Decarabia”
* Save previous source map for each node to support CSS concatenation
with multiple previous maps.
* Add `map.sourcesContent` option to add origin content to `sourcesContent`
inside map.
* Allow to set different place of output map in annotation comment.
* Allow to use arrays and `Root` in `Container#append` and same methods.
* Add `Root#prevMap` with information about previous map.
* Allow to use latest PostCSS from GitHub by npm.
* `Result` now is lazy and it will generate output CSS only if you use `css`
or `map` property.
* Use separated `map.prev` option to set previous map.
* Rename `inlineMap` option to `map.inline`.
* Rename `mapAnnotation` option to `map.annotation`.
* `Result#map` now return `SourceMapGenerator` object, instead of string.
* Run previous map autodetect only if input CSS contains annotation comment.
* Add `map: 'inline'` shortcut for `map: { inline: true }` option.
* `Node#source.file` now will contains absolute path.
* Clean `Declaration#between` style on node clone.
## 0.3.5
* Allow to use `Root` or `Result` as first argument in `process()`.
* Save parsed AST to `Result#root`.
## 0.3.4
* Better space symbol detect to read UTF-8 BOM correctly.
## 0.3.3
* Remove source map hacks by using new Mozillas `source-map` (by Simon Lydell).
## 0.3.2
* Add URI encoding support for inline source maps.
## 0.3.1
* Fix relative paths from previous source map.
* Safer space split in `Rule#selectors` (by Simon Lydell).
## 0.3 “Prince Seere”
* Add `Comment` node for comments between declarations or rules.
* Add source map annotation comment to output CSS.
* Allow to inline source map to annotation comment by data:uri.
* Fix source maps on Windows.
* Fix source maps for subdirectory (by Dmitry Nikitenko and Simon Lydell).
* Autodetect previous source map.
* Add `first` and `last` shortcuts to container nodes.
* Parse `!important` to separated property in `Declaration`.
* Allow to break iteration by returning `false`.
* Copy code style to new nodes.
* Add `eachInside` method to recursively iterate all nodes.
* Add `selectors` shortcut to get selectors array.
* Add `toResult` method to `Rule` to simplify work with several input files.
* Clean declarations `value`, rules `selector` and at-rules `params`
by storing spaces in `between` property.
## 0.2 “Duke Dantalion”
* Add source map support.
* Add shortcuts to create nodes.
* Method `process()` now returns object with `css` and `map` keys.
* Origin CSS file option was renamed from `file` to `from`.
* Rename `Node#remove()` method to `removeSelf()` to fix name conflict.
* Node source was moved to `source` property with origin file
and node end position.
* You can set own CSS generate function.
## 0.1 “Count Andromalius”
* Initial release.

View File

@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright 2013 Andrey Sitnik <andrey@sitnik.ru>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,344 @@
# PostCSS [![Travis Build Status][travis-img]][travis] [![AppVeyor Build Status][appveyor-img]][appveyor] [![Gitter][chat-img]][chat]
<img align="right" width="95" height="95"
alt="哲学家的石头 - PostCSS 的 logo"
src="http://postcss.github.io/postcss/logo.svg">
[appveyor-img]: https://img.shields.io/appveyor/ci/ai/postcss.svg?label=windows
[travis-img]: https://img.shields.io/travis/postcss/postcss.svg?label=unix
[chat-img]: https://img.shields.io/badge/Gitter-Join_the_PostCSS_chat-brightgreen.svg
[appveyor]: https://ci.appveyor.com/project/ai/postcss
[travis]: https://travis-ci.org/postcss/postcss
[chat]: https://gitter.im/postcss/postcss
PostCSS 是一个允许使用 JS 插件转换样式的工具。
这些插件可以检查lint你的 CSS支持 CSS Variables 和 Mixins
编译尚未被浏览器广泛支持的先进的 CSS 语法,内联图片,以及其它很多优秀的功能。
PostCSS 在工业界被广泛地应用其中不乏很多有名的行业领导者维基百科Twitter阿里巴巴
JetBrains。PostCSS 的 [Autoprefixer] 插件是最流行的 CSS 处理工具之一。
**Twitter 账号:** [@postcss](https://twitter.com/postcss)。<br>
**支持 / 讨论:** [Gitter](https://gitter.im/postcss/postcss)。<br>
如果需要 PostCSS 商业支持(如咨询,提升公司的前端文化,
PostCSS 插件),请联系 [Evil Martians](https://evilmartians.com/?utm_source=postcss)
邮箱 <surrender@evilmartians.com>
[Autoprefixer]: https://github.com/postcss/autoprefixer
<a href="https://evilmartians.com/?utm_source=postcss">
<img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg"
alt="由 Evil Martians 赞助" width="236" height="54">
</a>
## 插件
截止到目前PostCSS 有 200 多个插件。你可以在 [插件列表] 或 [搜索目录] 找到它们。
下方的列表是我们最喜欢的插件 - 它们很好地演示了我们可以用 PostCSS 做些什么。
如果你有任何新的想法,[开发 PostCSS 插件] 非常简单易上手。
[搜索目录]: http://postcss.parts
[插件列表]: https://github.com/postcss/postcss/blob/master/docs/plugins.md
### 解决全局 CSS 的问题
* [`postcss-use`] 允许你在 CSS 里明确地设置 PostCSS 插件,并且只在当前文件执行它们。
* [`postcss-modules`] 和 [`react-css-modules`] 可以自动以组件为单位隔绝 CSS 选择器。
* [`postcss-autoreset`] 是全局样式重置的又一个选择,它更适用于分离的组件。
* [`postcss-initial`] 添加了 `all: initial` 的支持,重置了所有继承的样式。
* [`cq-prolyfill`] 添加了容器查询的支持,允许添加响应于父元素宽度的样式.
### 提前使用先进的 CSS 特性
* [`autoprefixer`] 添加了 vendor 浏览器前缀,它使用 Can I Use 上面的数据。
* [`postcss-cssnext`] 允许你使用未来的 CSS 特性(包括 `autoprefixer`)。
* [`postcss-image-set-polyfill`] 为所有浏览器模拟了 [`image-set`] 函数逻辑。
### 更佳的 CSS 可读性
* [`precss`] 囊括了许多插件来支持类似 Sass 的特性,比如 CSS 变量套嵌mixins 等。
* [`postcss-sorting`] 给规则的内容以及@规则排序
* [`postcss-utilities`] 囊括了最常用的简写方式和书写帮助。
* [`short`] 添加并拓展了大量的缩写属性。
### 图片和字体
* [`postcss-assets`] 可以插入图片尺寸和内联文件。
* [`postcss-sprites`] 能生成雪碧图。
* [`font-magician`] 生成所有在 CSS 里需要的 `@font-face` 规则。
* [`postcss-inline-svg`] 允许你内联 SVG 并定制它的样式。
* [`postcss-write-svg`] 允许你在 CSS 里写简单的 SVG。
### 提示器Linters
* [`stylelint`] 是一个模块化的样式提示器。
* [`stylefmt`] 是一个能根据 `stylelint` 规则自动优化 CSS 格式的工具。
* [`doiuse`] 提示 CSS 的浏览器支持性,使用的数据来自于 Can I Use。
* [`colorguard`] 帮助你保持一个始终如一的调色板。
### 其它
* [`postcss-rtl`] 在单个 CSS 文件里组合了两个方向(左到右,右到左)的样式。
* [`cssnano`] 是一个模块化的 CSS 压缩器。
* [`lost`] 是一个功能强大的 `calc()` 栅格系统。
* [`rtlcss`] 镜像翻转 CSS 样式,适用于 right-to-left 的应用场景。
[`postcss-image-set-polyfill`]: https://github.com/SuperOl3g/postcss-image-set-polyfill
[`postcss-inline-svg`]: https://github.com/TrySound/postcss-inline-svg
[`react-css-modules`]: https://github.com/gajus/react-css-modules
[`postcss-autoreset`]: https://github.com/maximkoretskiy/postcss-autoreset
[`postcss-write-svg`]: https://github.com/jonathantneal/postcss-write-svg
[`postcss-utilities`]: https://github.com/ismamz/postcss-utilities
[`postcss-initial`]: https://github.com/maximkoretskiy/postcss-initial
[`postcss-sprites`]: https://github.com/2createStudio/postcss-sprites
[`postcss-modules`]: https://github.com/outpunk/postcss-modules
[`postcss-sorting`]: https://github.com/hudochenkov/postcss-sorting
[`postcss-cssnext`]: http://cssnext.io
[`postcss-assets`]: https://github.com/assetsjs/postcss-assets
[开发 PostCSS 插件]: https://github.com/postcss/postcss/blob/master/docs/writing-a-plugin.md
[`font-magician`]: https://github.com/jonathantneal/postcss-font-magician
[`autoprefixer`]: https://github.com/postcss/autoprefixer
[`cq-prolyfill`]: https://github.com/ausi/cq-prolyfill
[`postcss-rtl`]: https://github.com/vkalinichev/postcss-rtl
[`postcss-use`]: https://github.com/postcss/postcss-use
[`css-modules`]: https://github.com/css-modules/css-modules
[`colorguard`]: https://github.com/SlexAxton/css-colorguard
[`stylelint`]: https://github.com/stylelint/stylelint
[`image-set`]: https://drafts.csswg.org/css-images-4/#image-set-notation
[`stylefmt`]: https://github.com/morishitter/stylefmt
[`cssnano`]: http://cssnano.co
[`precss`]: https://github.com/jonathantneal/precss
[`doiuse`]: https://github.com/anandthakker/doiuse
[`rtlcss`]: https://github.com/MohammadYounes/rtlcss
[`short`]: https://github.com/jonathantneal/postcss-short
[`lost`]: https://github.com/peterramsing/lost
## 语法
PostCSS 可以转化样式到任意语法,不仅仅是 CSS。
如果还没有支持你最喜欢的语法,你可以编写一个解释器以及(或者)一个 stringifier 来拓展 PostCSS。
* [`sugarss`] 是一个以缩进为基础的语法,类似于 Sass 和 Stylus。
* [`postcss-html`] 允许你在 HTML / [Markdown](https://daringfireball.net/projects/markdown/syntax) / [Vue component](https://vue-loader.vuejs.org/) 里编写样式。
* [`postcss-scss`] 允许你使用 SCSS *(但并没有将 SCSS 编译到 CSS)*
* [`postcss-sass`] 允许你使用 Sass *(但并没有将 Sass 编译到 CSS)*
* [`postcss-less`] 允许你使用 Less *(但并没有将 LESS 编译到 CSS)*
* [`postcss-less-engine`] 允许你使用 Less *(并且使用真正的 Less.js 把 LESS 编译到 CSS)*
* [`postcss-js`] 允许你在 JS 里编写样式,或者转换成 React 的内联样式RadiumJSS。
* [`postcss-safe-parser`] 查找并修复 CSS 语法错误。
* [`midas`] 将 CSS 字符串转化成高亮的 HTML。
[`postcss-less-engine`]: https://github.com/Crunch/postcss-less
[`postcss-safe-parser`]: https://github.com/postcss/postcss-safe-parser
[`postcss-html`]: https://github.com/gucong3000/postcss-html
[`postcss-scss`]: https://github.com/postcss/postcss-scss
[`postcss-sass`]: https://github.com/AleshaOleg/postcss-sass
[`postcss-less`]: https://github.com/webschik/postcss-less
[`postcss-js`]: https://github.com/postcss/postcss-js
[`sugarss`]: https://github.com/postcss/sugarss
[`midas`]: https://github.com/ben-eb/midas
## 文章
* [一些你对 PostCSS 可能产生的误解](http://julian.io/some-things-you-may-think-about-postcss-and-you-might-be-wrong)
* [PostCSS 究竟是什么,是做什么的](http://davidtheclark.com/its-time-for-everyone-to-learn-about-postcss)
* [PostCSS 指南](http://webdesign.tutsplus.com/series/postcss-deep-dive--cms-889)
你可以在 [awesome-postcss](https://github.com/jjaderg/awesome-postcss) 列表里找到更多优秀的文章和视频。
## 书籍
* Alex Libby, Packt 的 [网页设计之精通 PostCSS](https://www.packtpub.com/web-development/mastering-postcss-web-design) (2016年6月)
## 使用方法
你可以通过简单的两步便开始使用 PostCSS
1. 在你的构建工具中查找并添加 PostCSS 拓展。
2. [选择插件]并将它们添加到你的 PostCSS 处理队列中。
[选择插件]: http://postcss.parts
### Webpack
`webpack.config.js` 里使用 [`postcss-loader`] :
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
importLoaders: 1,
}
},
{
loader: 'postcss-loader'
}
]
}
]
}
}
```
然后创建 `postcss.config.js`:
```js
module.exports = {
plugins: [
require('precss'),
require('autoprefixer')
]
}
```
[`postcss-loader`]: https://github.com/postcss/postcss-loader
### Gulp
使用 [`gulp-postcss`] 和 [`gulp-sourcemaps`].
```js
gulp.task('css', function () {
var postcss = require('gulp-postcss');
var sourcemaps = require('gulp-sourcemaps');
return gulp.src('src/**/*.css')
.pipe( sourcemaps.init() )
.pipe( postcss([ require('precss'), require('autoprefixer') ]) )
.pipe( sourcemaps.write('.') )
.pipe( gulp.dest('build/') );
});
```
[`gulp-sourcemaps`]: https://github.com/floridoo/gulp-sourcemaps
[`gulp-postcss`]: https://github.com/postcss/gulp-postcss
### npm run / CLI
如果需要在你的命令行界面或 npm 脚本里使用 PostCSS你可以使用 [`postcss-cli`]。
```sh
postcss --use autoprefixer -c options.json -o main.css css/*.css
```
[`postcss-cli`]: https://github.com/postcss/postcss-cli
### 浏览器
如果你想编译浏览器里的 CSS 字符串(例如像 CodePen 一样的在线编辑器),
只需使用 [Browserify] 或 [webpack]。它们会把 PostCSS 和插件文件打包进一个独立文件。
如果想要在 React 内联样式JSSRadium其它 [CSS-in-JS] 里使用 PostCSS
你可以用 [`postcss-js`] 然后转换样式对象。
```js
var postcss = require('postcss-js');
var prefixer = postcss.sync([ require('autoprefixer') ]);
prefixer({ display: 'flex' }); //=> { display: ['-webkit-box', '-webkit-flex', '-ms-flexbox', 'flex'] }
```
[`postcss-js`]: https://github.com/postcss/postcss-js
[Browserify]: http://browserify.org/
[CSS-in-JS]: https://github.com/MicheleBertoli/css-in-js
[webpack]: https://webpack.github.io/
### 运行器
* **Grunt**: [`grunt-postcss`](https://github.com/nDmitry/grunt-postcss)
* **HTML**: [`posthtml-postcss`](https://github.com/posthtml/posthtml-postcss)
* **Stylus**: [`poststylus`](https://github.com/seaneking/poststylus)
* **Rollup**: [`rollup-plugin-postcss`](https://github.com/egoist/rollup-plugin-postcss)
* **Brunch**: [`postcss-brunch`](https://github.com/brunch/postcss-brunch)
* **Broccoli**: [`broccoli-postcss`](https://github.com/jeffjewiss/broccoli-postcss)
* **Meteor**: [`postcss`](https://atmospherejs.com/juliancwirko/postcss)
* **ENB**: [`enb-postcss`](https://github.com/awinogradov/enb-postcss)
* **Taskr**: [`taskr-postcss`](https://github.com/lukeed/taskr/tree/master/packages/postcss)
* **Start**: [`start-postcss`](https://github.com/start-runner/postcss)
* **Connect/Express**: [`postcss-middleware`](https://github.com/jedmao/postcss-middleware)
### JS API
对于其它的应用环境,你可以使用 JS API
```js
const fs = require('fs');
const postcss = require('postcss');
const precss = require('precss');
const autoprefixer = require('autoprefixer');
fs.readFile('src/app.css', (err, css) => {
postcss([precss, autoprefixer])
.process(css, { from: 'src/app.css', to: 'dest/app.css' })
.then(result => {
fs.writeFile('dest/app.css', result.css);
if ( result.map ) fs.writeFile('dest/app.css.map', result.map);
});
});
```
阅读 [PostCSS API 文档] 获取更多有关 JS API 的信息.
所有的 PostCSS 运行器应当通过 [PostCSS 运行器指南]。
[PostCSS 运行器指南]: https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md
[PostCSS API 文档]: http://api.postcss.org/postcss.html
### 配置选项
绝大多数 PostCSS 运行器接受两个参数:
* 一个包含所需插件的数组
* 一个配置选项的对象
常见的选项:
* `syntax`: 一个提供了语法解释器和 stringifier 的对象。
* `parser`: 一个特殊的语法解释器(例如 [SCSS])。
* `stringifier`: 一个特殊的语法 output 生成器(例如 [Midas])。
* `map`: [source map 选项].
* `from`: input 文件名称(大多数运行器自动设置了这个)。
* `to`: output 文件名称(大多数运行器自动设置了这个)。
[source map 选项]: https://github.com/postcss/postcss/blob/master/docs/source-maps.md
[Midas]: https://github.com/ben-eb/midas
[SCSS]: https://github.com/postcss/postcss-scss
### Atom
* [`language-postcss`] 添加了 PostCSS 和 [SugarSS] 代码高亮。
* [`source-preview-postcss`] 在一个独立窗口里实时预览生成的 CSS。
[SugarSS]: https://github.com/postcss/sugarss
### Sublime Text
* [`Syntax-highlighting-for-PostCSS`] 添加了 PostCSS 代码高亮。
[`Syntax-highlighting-for-PostCSS`]: https://github.com/hudochenkov/Syntax-highlighting-for-PostCSS
[`source-preview-postcss`]: https://atom.io/packages/source-preview-postcss
[`language-postcss`]: https://atom.io/packages/language-postcss
### Vim
* [`postcss.vim`] 添加了 PostCSS 代码高亮。
[`postcss.vim`]: https://github.com/stephenway/postcss.vim
### WebStorm
自 WebStorm 2016.3 开始,[提供了] 内建的 PostCSS 支持。
[提供了]: https://blog.jetbrains.com/webstorm/2016/08/webstorm-2016-3-early-access-preview/

View File

@@ -0,0 +1,367 @@
# PostCSS [![Travis Build Status][travis-img]][travis] [![AppVeyor Build Status][appveyor-img]][appveyor] [![Gitter][chat-img]][chat]
<img align="right" width="95" height="95"
alt="Philosophers stone, logo of PostCSS"
src="http://postcss.github.io/postcss/logo.svg">
[appveyor-img]: https://img.shields.io/appveyor/ci/ai/postcss.svg?label=windows
[travis-img]: https://img.shields.io/travis/postcss/postcss.svg?label=unix
[chat-img]: https://img.shields.io/badge/Gitter-Join_the_PostCSS_chat-brightgreen.svg
[appveyor]: https://ci.appveyor.com/project/ai/postcss
[travis]: https://travis-ci.org/postcss/postcss
[chat]: https://gitter.im/postcss/postcss
PostCSS is a tool for transforming styles with JS plugins.
These plugins can lint your CSS, support variables and mixins,
transpile future CSS syntax, inline images, and more.
PostCSS is used by industry leaders including Wikipedia, Twitter, Alibaba,
and JetBrains. The [Autoprefixer] PostCSS plugin is one of the most popular
CSS processors.
**Twitter account:** [@postcss](https://twitter.com/postcss).<br>
**VK.com page:** [postcss](https://vk.com/postcss).<br>
**Support / Discussion:** [Gitter](https://gitter.im/postcss/postcss).<br>
**中文翻译**: [`README.cn.md`](./README.cn.md).
For PostCSS commercial support (consulting, improving the front-end culture
of your company, PostCSS plugins), contact [Evil Martians](https://evilmartians.com/?utm_source=postcss)
at <surrender@evilmartians.com>.
[Autoprefixer]: https://github.com/postcss/autoprefixer
<a href="https://evilmartians.com/?utm_source=postcss">
<img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg"
alt="Sponsored by Evil Martians" width="236" height="54">
</a>
## Plugins
Currently, PostCSS has more than 200 plugins. You can find all of the plugins
in the [plugins list] or in the [searchable catalog]. Below is a list
of our favorite plugins — the best demonstrations of what can be built
on top of PostCSS.
If you have any new ideas, [PostCSS plugin development] is really easy.
[searchable catalog]: http://postcss.parts
[plugins list]: https://github.com/postcss/postcss/blob/master/docs/plugins.md
### Solve Global CSS Problem
* [`postcss-use`] allows you to explicitly set PostCSS plugins within CSS
and execute them only for the current file.
* [`postcss-modules`] and [`react-css-modules`] automatically isolate
selectors within components.
* [`postcss-autoreset`] is an alternative to using a global reset
that is better for isolatable components.
* [`postcss-initial`] adds `all: initial` support, which resets
all inherited styles.
* [`cq-prolyfill`] adds container query support, allowing styles that respond
to the width of the parent.
### Use Future CSS, Today
* [`autoprefixer`] adds vendor prefixes, using data from Can I Use.
* [`postcss-cssnext`] allows you to use future CSS features today
(includes `autoprefixer`).
* [`postcss-image-set-polyfill`] emulates [`image-set`] function logic for all browsers
### Better CSS Readability
* [`precss`] contains plugins for Sass-like features, like variables, nesting,
and mixins.
* [`postcss-sorting`] sorts the content of rules and at-rules.
* [`postcss-utilities`] includes the most commonly used shortcuts and helpers.
* [`short`] adds and extends numerous shorthand properties.
### Images and Fonts
* [`postcss-assets`] inserts image dimensions and inlines files.
* [`postcss-sprites`] generates image sprites.
* [`font-magician`] generates all the `@font-face` rules needed in CSS.
* [`postcss-inline-svg`] allows you to inline SVG and customize its styles.
* [`postcss-write-svg`] allows you to write simple SVG directly in your CSS.
### Linters
* [`stylelint`] is a modular stylesheet linter.
* [`stylefmt`] is a tool that automatically formats CSS
according `stylelint` rules.
* [`doiuse`] lints CSS for browser support, using data from Can I Use.
* [`colorguard`] helps you maintain a consistent color palette.
### Other
* [`postcss-rtl`] combines both-directional (left-to-right and right-to-left) styles in one CSS file.
* [`cssnano`] is a modular CSS minifier.
* [`lost`] is a feature-rich `calc()` grid system.
* [`rtlcss`] mirrors styles for right-to-left locales.
[`postcss-image-set-polyfill`]: https://github.com/SuperOl3g/postcss-image-set-polyfill
[PostCSS plugin development]: https://github.com/postcss/postcss/blob/master/docs/writing-a-plugin.md
[`postcss-inline-svg`]: https://github.com/TrySound/postcss-inline-svg
[`react-css-modules`]: https://github.com/gajus/react-css-modules
[`postcss-autoreset`]: https://github.com/maximkoretskiy/postcss-autoreset
[`postcss-write-svg`]: https://github.com/jonathantneal/postcss-write-svg
[`postcss-utilities`]: https://github.com/ismamz/postcss-utilities
[`postcss-initial`]: https://github.com/maximkoretskiy/postcss-initial
[`postcss-sprites`]: https://github.com/2createStudio/postcss-sprites
[`postcss-modules`]: https://github.com/outpunk/postcss-modules
[`postcss-sorting`]: https://github.com/hudochenkov/postcss-sorting
[`postcss-cssnext`]: http://cssnext.io
[`postcss-assets`]: https://github.com/assetsjs/postcss-assets
[`font-magician`]: https://github.com/jonathantneal/postcss-font-magician
[`autoprefixer`]: https://github.com/postcss/autoprefixer
[`cq-prolyfill`]: https://github.com/ausi/cq-prolyfill
[`postcss-rtl`]: https://github.com/vkalinichev/postcss-rtl
[`postcss-use`]: https://github.com/postcss/postcss-use
[`css-modules`]: https://github.com/css-modules/css-modules
[`colorguard`]: https://github.com/SlexAxton/css-colorguard
[`stylelint`]: https://github.com/stylelint/stylelint
[`image-set`]: https://drafts.csswg.org/css-images-4/#image-set-notation
[`stylefmt`]: https://github.com/morishitter/stylefmt
[`cssnano`]: http://cssnano.co
[`precss`]: https://github.com/jonathantneal/precss
[`doiuse`]: https://github.com/anandthakker/doiuse
[`rtlcss`]: https://github.com/MohammadYounes/rtlcss
[`short`]: https://github.com/jonathantneal/postcss-short
[`lost`]: https://github.com/peterramsing/lost
## Syntaxes
PostCSS can transform styles in any syntax, not just CSS.
If there is not yet support for your favorite syntax,
you can write a parser and/or stringifier to extend PostCSS.
* [`sugarss`] is a indent-based syntax like Sass or Stylus.
* [`postcss-html`] allows you to write styles in HTML / [Markdown](https://daringfireball.net/projects/markdown/syntax) / [Vue component](https://vue-loader.vuejs.org/)
* [`postcss-scss`] allows you to work with SCSS
*(but does not compile SCSS to CSS)*.
* [`postcss-sass`] allows you to work with Sass
*(but does not compile Sass to CSS)*.
* [`postcss-less`] allows you to work with Less
*(but does not compile LESS to CSS)*.
* [`postcss-less-engine`] allows you to work with Less
*(and DOES compile LESS to CSS using true Less.js evaluation)*.
* [`postcss-js`] allows you to write styles in JS or transform
React Inline Styles, Radium or JSS.
* [`postcss-safe-parser`] finds and fixes CSS syntax errors.
* [`midas`] converts a CSS string to highlighted HTML.
[`postcss-less-engine`]: https://github.com/Crunch/postcss-less
[`postcss-safe-parser`]: https://github.com/postcss/postcss-safe-parser
[`postcss-html`]: https://github.com/gucong3000/postcss-html
[`postcss-scss`]: https://github.com/postcss/postcss-scss
[`postcss-sass`]: https://github.com/AleshaOleg/postcss-sass
[`postcss-less`]: https://github.com/webschik/postcss-less
[`postcss-js`]: https://github.com/postcss/postcss-js
[`sugarss`]: https://github.com/postcss/sugarss
[`midas`]: https://github.com/ben-eb/midas
## Articles
* [Some things you may think about PostCSS… and you might be wrong](http://julian.io/some-things-you-may-think-about-postcss-and-you-might-be-wrong)
* [What PostCSS Really Is; What It Really Does](http://davidtheclark.com/its-time-for-everyone-to-learn-about-postcss)
* [PostCSS Guides](http://webdesign.tutsplus.com/series/postcss-deep-dive--cms-889)
More articles and videos you can find on [awesome-postcss](https://github.com/jjaderg/awesome-postcss) list.
## Books
* [Mastering PostCSS for Web Design](https://www.packtpub.com/web-development/mastering-postcss-web-design) by Alex Libby, Packt. (June 2016)
## Usage
You can start using PostCSS in just two steps:
1. Find and add PostCSS extensions for your build tool.
2. [Select plugins] and add them to your PostCSS process.
[Select plugins]: http://postcss.parts
### Webpack
Use [`postcss-loader`] in `webpack.config.js`:
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
importLoaders: 1,
}
},
{
loader: 'postcss-loader'
}
]
}
]
}
}
```
Then create `postcss.config.js`:
```js
module.exports = {
plugins: [
require('precss'),
require('autoprefixer')
]
}
```
[`postcss-loader`]: https://github.com/postcss/postcss-loader
### Gulp
Use [`gulp-postcss`] and [`gulp-sourcemaps`].
```js
gulp.task('css', function () {
var postcss = require('gulp-postcss');
var sourcemaps = require('gulp-sourcemaps');
return gulp.src('src/**/*.css')
.pipe( sourcemaps.init() )
.pipe( postcss([ require('precss'), require('autoprefixer') ]) )
.pipe( sourcemaps.write('.') )
.pipe( gulp.dest('build/') );
});
```
[`gulp-sourcemaps`]: https://github.com/floridoo/gulp-sourcemaps
[`gulp-postcss`]: https://github.com/postcss/gulp-postcss
### npm run / CLI
To use PostCSS from your command-line interface or with npm scripts
there is [`postcss-cli`].
```sh
postcss --use autoprefixer -c options.json -o main.css css/*.css
```
[`postcss-cli`]: https://github.com/postcss/postcss-cli
### Browser
If you want to compile CSS string in browser (for instance, in live edit
tools like CodePen), just use [Browserify] or [webpack]. They will pack
PostCSS and plugins files into a single file.
To apply PostCSS plugins to React Inline Styles, JSS, Radium
and other [CSS-in-JS], you can use [`postcss-js`] and transforms style objects.
```js
var postcss = require('postcss-js');
var prefixer = postcss.sync([ require('autoprefixer') ]);
prefixer({ display: 'flex' }); //=> { display: ['-webkit-box', '-webkit-flex', '-ms-flexbox', 'flex'] }
```
[`postcss-js`]: https://github.com/postcss/postcss-js
[Browserify]: http://browserify.org/
[CSS-in-JS]: https://github.com/MicheleBertoli/css-in-js
[webpack]: https://webpack.github.io/
### Runners
* **Grunt**: [`grunt-postcss`](https://github.com/nDmitry/grunt-postcss)
* **HTML**: [`posthtml-postcss`](https://github.com/posthtml/posthtml-postcss)
* **Stylus**: [`poststylus`](https://github.com/seaneking/poststylus)
* **Rollup**: [`rollup-plugin-postcss`](https://github.com/egoist/rollup-plugin-postcss)
* **Brunch**: [`postcss-brunch`](https://github.com/brunch/postcss-brunch)
* **Broccoli**: [`broccoli-postcss`](https://github.com/jeffjewiss/broccoli-postcss)
* **Meteor**: [`postcss`](https://atmospherejs.com/juliancwirko/postcss)
* **ENB**: [`enb-postcss`](https://github.com/awinogradov/enb-postcss)
* **Taskr**: [`taskr-postcss`](https://github.com/lukeed/taskr/tree/master/packages/postcss)
* **Start**: [`start-postcss`](https://github.com/start-runner/postcss)
* **Connect/Express**: [`postcss-middleware`](https://github.com/jedmao/postcss-middleware)
### JS API
For other environments, you can use the JS API:
```js
const fs = require('fs');
const postcss = require('postcss');
const precss = require('precss');
const autoprefixer = require('autoprefixer');
fs.readFile('src/app.css', (err, css) => {
postcss([precss, autoprefixer])
.process(css, { from: 'src/app.css', to: 'dest/app.css' })
.then(result => {
fs.writeFile('dest/app.css', result.css);
if ( result.map ) fs.writeFile('dest/app.css.map', result.map);
});
});
```
Read the [PostCSS API documentation] for more details about the JS API.
All PostCSS runners should pass [PostCSS Runner Guidelines].
[PostCSS Runner Guidelines]: https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md
[PostCSS API documentation]: http://api.postcss.org/postcss.html
### Options
Most PostCSS runners accept two parameters:
* An array of plugins.
* An object of options.
Common options:
* `syntax`: an object providing a syntax parser and a stringifier.
* `parser`: a special syntax parser (for example, [SCSS]).
* `stringifier`: a special syntax output generator (for example, [Midas]).
* `map`: [source map options].
* `from`: the input file name (most runners set it automatically).
* `to`: the output file name (most runners set it automatically).
[source map options]: https://github.com/postcss/postcss/blob/master/docs/source-maps.md
[Midas]: https://github.com/ben-eb/midas
[SCSS]: https://github.com/postcss/postcss-scss
## Editors & IDE Integration
### Atom
* [`language-postcss`] adds PostCSS and [SugarSS] highlight.
* [`source-preview-postcss`] previews your output CSS in a separate, live pane.
[SugarSS]: https://github.com/postcss/sugarss
### Sublime Text
* [`Syntax-highlighting-for-PostCSS`] adds PostCSS highlight.
[`Syntax-highlighting-for-PostCSS`]: https://github.com/hudochenkov/Syntax-highlighting-for-PostCSS
[`source-preview-postcss`]: https://atom.io/packages/source-preview-postcss
[`language-postcss`]: https://atom.io/packages/language-postcss
### Vim
* [`postcss.vim`] adds PostCSS highlight.
[`postcss.vim`]: https://github.com/stephenway/postcss.vim
### WebStorm
WebStorm 2016.3 [has] built-in PostCSS support.
[has]: https://blog.jetbrains.com/webstorm/2016/08/webstorm-2016-3-early-access-preview/

View File

@@ -0,0 +1,195 @@
# PostCSS Plugin Guidelines
A PostCSS plugin is a function that receives and, usually,
transforms a CSS AST from the PostCSS parser.
The rules below are *mandatory* for all PostCSS plugins.
See also [ClojureWerkzs recommendations] for open source projects.
[ClojureWerkzs recommendations]: http://blog.clojurewerkz.org/blog/2013/04/20/how-to-make-your-open-source-project-really-awesome/
## 1. API
### 1.1 Clear name with `postcss-` prefix
The plugins purpose should be clear just by reading its name.
If you wrote a transpiler for CSS 4 Custom Media, `postcss-custom-media`
would be a good name. If you wrote a plugin to support mixins,
`postcss-mixins` would be a good name.
The prefix `postcss-` shows that the plugin is part of the PostCSS ecosystem.
This rule is not mandatory for plugins that can run as independent tools,
without the user necessarily knowing that it is powered by
PostCSS — for example, [cssnext] and [Autoprefixer].
[Autoprefixer]: https://github.com/postcss/autoprefixer
[cssnext]: http://cssnext.io/
### 1.2. Do one thing, and do it well
Do not create multitool plugins. Several small, one-purpose plugins bundled into
a plugin pack is usually a better solution.
For example, [cssnext] contains many small plugins,
one for each W3C specification. And [cssnano] contains a separate plugin
for each of its optimization.
[cssnext]: http://cssnext.io/
[cssnano]: https://github.com/ben-eb/cssnano
### 1.3. Do not use mixins
Preprocessors libraries like Compass provide an API with mixins.
PostCSS plugins are different.
A plugin cannot be just a set of mixins for [postcss-mixins].
To achieve your goal, consider transforming valid CSS
or using custom at-rules and custom properties.
[postcss-mixins]: https://github.com/postcss/postcss-mixins
### 1.4. Create plugin by `postcss.plugin`
By wrapping your function in this method,
you are hooking into a common plugin API:
```js
module.exports = postcss.plugin('plugin-name', function (opts) {
return function (root, result) {
// Plugin code
};
});
```
## 2. Processing
### 2.1. Plugin must be tested
A CI service like [Travis] is also recommended for testing code in
different environments. You should test in (at least) Node.js [active LTS](https://github.com/nodejs/LTS) and current stable version.
[Travis]: https://travis-ci.org/
### 2.2. Use asynchronous methods whenever possible
For example, use `fs.writeFile` instead of `fs.writeFileSync`:
```js
postcss.plugin('plugin-sprite', function (opts) {
return function (root, result) {
return new Promise(function (resolve, reject) {
var sprite = makeSprite();
fs.writeFile(opts.file, function (err) {
if ( err ) return reject(err);
resolve();
})
});
};
});
```
### 2.3. Set `node.source` for new nodes
Every node must have a relevant `source` so PostCSS can generate
an accurate source map.
So if you add new declaration based on some existing declaration, you should
clone the existing declaration in order to save that original `source`.
```js
if ( needPrefix(decl.prop) ) {
decl.cloneBefore({ prop: '-webkit-' + decl.prop });
}
```
You can also set `source` directly, copying from some existing node:
```js
if ( decl.prop === 'animation' ) {
var keyframe = createAnimationByName(decl.value);
keyframes.source = decl.source;
decl.root().append(keyframes);
}
```
### 2.4. Use only the public PostCSS API
PostCSS plugins must not rely on undocumented properties or methods,
which may be subject to change in any minor release. The public API
is described in [API docs].
[API docs]: http://api.postcss.org/
## 3. Errors
### 3.1. Use `node.error` on CSS relevant errors
If you have an error because of input CSS (like an unknown name
in a mixin plugin) you should use `node.error` to create an error
that includes source position:
```js
if ( typeof mixins[name] === 'undefined' ) {
throw decl.error('Unknown mixin ' + name, { plugin: 'postcss-mixins' });
}
```
### 3.2. Use `result.warn` for warnings
Do not print warnings with `console.log` or `console.warn`,
because some PostCSS runner may not allow console output.
```js
if ( outdated(decl.prop) ) {
result.warn(decl.prop + ' is outdated', { node: decl });
}
```
If CSS input is a source of the warning, the plugin must set the `node` option.
## 4. Documentation
### 4.1. Document your plugin in English
PostCSS plugins must have their `README.md` written in English. Do not be afraid
of your English skills, as the open source community will fix your errors.
Of course, you are welcome to write documentation in other languages;
just name them appropriately (e.g. `README.ja.md`).
### 4.2. Include input and output examples
The plugin's `README.md` must contain example input and output CSS.
A clear example is the best way to describe how your plugin works.
The first section of the `README.md` is a good place to put examples.
See [postcss-opacity](https://github.com/iamvdo/postcss-opacity) for an example.
Of course, this guideline does not apply if your plugin does not
transform the CSS.
### 4.3. Maintain a changelog
PostCSS plugins must describe the changes of all their releases
in a separate file, such as `CHANGELOG.md`, `History.md`, or [GitHub Releases].
Visit [Keep A Changelog] for more information about how to write one of these.
Of course, you should be using [SemVer].
[Keep A Changelog]: http://keepachangelog.com/
[GitHub Releases]: https://help.github.com/articles/creating-releases/
[SemVer]: http://semver.org/
### 4.4. Include `postcss-plugin` keyword in `package.json`
PostCSS plugins written for npm must have the `postcss-plugin` keyword
in their `package.json`. This special keyword will be useful for feedback about
the PostCSS ecosystem.
For packages not published to npm, this is not mandatory, but is recommended
if the package format can contain keywords.

View File

@@ -0,0 +1,143 @@
# PostCSS Runner Guidelines
A PostCSS runner is a tool that processes CSS through a user-defined list
of plugins; for example, [`postcss-cli`] or [`gulppostcss`].
These rules are mandatory for any such runners.
For single-plugin tools, like [`gulp-autoprefixer`],
these rules are not mandatory but are highly recommended.
See also [ClojureWerkzs recommendations] for open source projects.
[ClojureWerkzs recommendations]: http://blog.clojurewerkz.org/blog/2013/04/20/how-to-make-your-open-source-project-really-awesome/
[`gulp-autoprefixer`]: https://github.com/sindresorhus/gulp-autoprefixer
[`gulppostcss`]: https://github.com/w0rm/gulp-postcss
[`postcss-cli`]: https://github.com/postcss/postcss-cli
## 1. API
### 1.1. Accept functions in plugin parameters
If your runner uses a config file, it must be written in JavaScript, so that
it can support plugins which accept a function, such as [`postcss-assets`]:
```js
module.exports = [
require('postcss-assets')({
cachebuster: function (file) {
return fs.statSync(file).mtime.getTime().toString(16);
}
})
];
```
[`postcss-assets`]: https://github.com/borodean/postcss-assets
## 2. Processing
### 2.1. Set `from` and `to` processing options
To ensure that PostCSS generates source maps and displays better syntax errors,
runners must specify the `from` and `to` options. If your runner does not handle
writing to disk (for example, a gulp transform), you should set both options
to point to the same file:
```js
processor.process({ from: file.path, to: file.path });
```
### 2.2. Use only the asynchronous API
PostCSS runners must use only the asynchronous API.
The synchronous API is provided only for debugging, is slower,
and cant work with asynchronous plugins.
```js
processor.process(opts).then(function (result) {
// processing is finished
});
```
### 2.3. Use only the public PostCSS API
PostCSS runners must not rely on undocumented properties or methods,
which may be subject to change in any minor release. The public API
is described in [API docs].
[API docs]: http://api.postcss.org/
## 3. Output
### 3.1. Dont show JS stack for `CssSyntaxError`
PostCSS runners must not show a stack trace for CSS syntax errors,
as the runner can be used by developers who are not familiar with JavaScript.
Instead, handle such errors gracefully:
```js
processor.process(opts).catch(function (error) {
if ( error.name === 'CssSyntaxError' ) {
process.stderr.write(error.message + error.showSourceCode());
} else {
throw error;
}
});
```
### 3.2. Display `result.warnings()`
PostCSS runners must output warnings from `result.warnings()`:
```js
result.warnings().forEach(function (warn) {
process.stderr.write(warn.toString());
});
```
See also [postcss-log-warnings] and [postcss-messages] plugins.
[postcss-log-warnings]: https://github.com/davidtheclark/postcss-log-warnings
[postcss-messages]: https://github.com/postcss/postcss-messages
### 3.3. Allow the user to write source maps to different files
PostCSS by default will inline source maps in the generated file; however,
PostCSS runners must provide an option to save the source map in a different
file:
```js
if ( result.map ) {
fs.writeFile(opts.to + '.map', result.map.toString());
}
```
## 4. Documentation
### 4.1. Document your runner in English
PostCSS runners must have their `README.md` written in English. Do not be afraid
of your English skills, as the open source community will fix your errors.
Of course, you are welcome to write documentation in other languages;
just name them appropriately (e.g. `README.ja.md`).
### 4.2. Maintain a changelog
PostCSS runners must describe changes of all releases in a separate file,
such as `ChangeLog.md`, `History.md`, or with [GitHub Releases].
Visit [Keep A Changelog] for more information on how to write one of these.
Of course you should use [SemVer].
[Keep A Changelog]: http://keepachangelog.com/
[GitHub Releases]: https://help.github.com/articles/creating-releases/
[SemVer]: http://semver.org/
### 4.3. `postcss-runner` keyword in `package.json`
PostCSS runners written for npm must have the `postcss-runner` keyword
in their `package.json`. This special keyword will be useful for feedback about
the PostCSS ecosystem.
For packages not published to npm, this is not mandatory, but recommended
if the package format is allowed to contain keywords.

View File

@@ -0,0 +1,74 @@
# PostCSS and Source Maps
PostCSS has great [source maps] support. It can read and interpret maps
from previous transformation steps, autodetect the format that you expect,
and output both external and inline maps.
To ensure that you generate an accurate source map, you must indicate the input
and output CSS file paths — using the options `from` and `to`, respectively.
To generate a new source map with the default options, simply set `map: true`.
This will generate an inline source map that contains the source content.
If you dont want the map inlined, you can set `map.inline: false`.
```js
processor
.process(css, {
from: 'app.sass.css',
to: 'app.css',
map: { inline: false },
})
.then(function (result) {
result.map //=> '{ "version":3,
// "file":"app.css",
// "sources":["app.sass"],
// "mappings":"AAAA,KAAI" }'
});
```
If PostCSS finds source maps from a previous transformation,
it will automatically update that source map with the same options.
## Options
If you want more control over source map generation, you can define the `map`
option as an object with the following parameters:
* `inline` boolean: indicates that the source map should be embedded
in the output CSS as a Base64-encoded comment. By default, it is `true`.
But if all previous maps are external, not inline, PostCSS will not embed
the map even if you do not set this option.
If you have an inline source map, the `result.map` property will be empty,
as the source map will be contained within the text of `result.css`.
* `prev` string, object, boolean or function: source map content from
a previous processing step (for example, Sass compilation).
PostCSS will try to read the previous source map automatically
(based on comments within the source CSS), but you can use this option
to identify it manually. If desired, you can omit the previous map
with `prev: false`.
* `sourcesContent` boolean: indicates that PostCSS should set the origin
content (for example, Sass source) of the source map. By default,
it is `true`. But if all previous maps do not contain sources content,
PostCSS will also leave it out even if you do not set this option.
* `annotation` boolean or string: indicates that PostCSS should add annotation
comments to the CSS. By default, PostCSS will always add a comment with a path
to the source map. PostCSS will not add annotations to CSS files that
do not contain any comments.
By default, PostCSS presumes that you want to save the source map as
`opts.to + '.map'` and will use this path in the annotation comment.
A different path can be set by providing a string value for `annotation`.
If you have set `inline: true`, annotation cannot be disabled.
* `from` string: by default, PostCSS will set the `sources` property of the map
to the value of the `from` option. If you want to override this behaviour, you
can use `map.from` to explicitly set the source map's `sources` property.
Path should be absolute or relative from generated file
(`to` option in `process()` method).
[source maps]: http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/

View File

@@ -0,0 +1,231 @@
# How to Write Custom Syntax
PostCSS can transform styles in any syntax, and is not limited to just CSS.
By writing a custom syntax, you can transform styles in any desired format.
Writing a custom syntax is much harder than writing a PostCSS plugin, but
it is an awesome adventure.
There are 3 types of PostCSS syntax packages:
* **Parser** to parse input string to nodes tree.
* **Stringifier** to generate output string by nodes tree.
* **Syntax** contains both parser and stringifier.
## Syntax
A good example of a custom syntax is [SCSS]. Some users may want to transform
SCSS sources with PostCSS plugins, for example if they need to add vendor
prefixes or change the property order. So this syntax should output SCSS from
an SCSS input.
The syntax API is a very simple plain object, with `parse` & `stringify`
functions:
```js
module.exports = {
parse: require('./parse'),
stringify: require('./stringify')
};
```
[SCSS]: https://github.com/postcss/postcss-scss
## Parser
A good example of a parser is [Safe Parser], which parses malformed/broken CSS.
Because there is no point to generate broken output, this package only provides
a parser.
The parser API is a function which receives a string & returns a [`Root`] node.
The second argument is a function which receives an object with PostCSS options.
```js
var postcss = require('postcss');
module.exports = function (css, opts) {
var root = postcss.root();
// Add other nodes to root
return root;
};
```
[Safe Parser]: https://github.com/postcss/postcss-safe-parser
[`Root`]: http://api.postcss.org/Root.html
### Main Theory
There are many books about parsers; but do not worry because CSS syntax is
very easy, and so the parser will be much simpler than a programming language
parser.
The default PostCSS parser contains two steps:
1. [Tokenizer] which reads input string character by character and builds a
tokens array. For example, it joins space symbols to a `['space', '\n ']`
token, and detects strings to a `['string', '"\"{"']` token.
2. [Parser] which reads the tokens array, creates node instances and
builds a tree.
[Tokenizer]: https://github.com/postcss/postcss/blob/master/lib/tokenize.es6
[Parser]: https://github.com/postcss/postcss/blob/master/lib/parser.es6
### Performance
Parsing input is often the most time consuming task in CSS processors. So it
is very important to have a fast parser.
The main rule of optimization is that there is no performance without a
benchmark. You can look at [PostCSS benchmarks] to build your own.
Of parsing tasks, the tokenize step will often take the most time, so its
performance should be prioritized. Unfortunately, classes, functions and
high level structures can slow down your tokenizer. Be ready to write dirty
code with repeated statements. This is why it is difficult to extend the
default [PostCSS tokenizer]; copy & paste will be a necessary evil.
Second optimization is using character codes instead of strings.
```js
// Slow
string[i] === '{';
// Fast
const OPEN_CURLY = 123; // `{'
string.charCodeAt(i) === OPEN_CURLY;
```
Third optimization is “fast jumps”. If you find open quotes, you can find
next closing quote much faster by `indexOf`:
```js
// Simple jump
next = string.indexOf('"', currentPosition + 1);
// Jump by RegExp
regexp.lastIndex = currentPosion + 1;
regexp.text(string);
next = regexp.lastIndex;
```
The parser can be a well written class. There is no need in copy-paste and
hardcore optimization there. You can extend the default [PostCSS parser].
[PostCSS benchmarks]: https://github.com/postcss/benchmark
[PostCSS tokenizer]: https://github.com/postcss/postcss/blob/master/lib/tokenize.es6
[PostCSS parser]: https://github.com/postcss/postcss/blob/master/lib/parser.es6
### Node Source
Every node should have `source` property to generate correct source map.
This property contains `start` and `end` properties with `{ line, column }`,
and `input` property with an [`Input`] instance.
Your tokenizer should save the original position so that you can propagate
the values to the parser, to ensure that the source map is correctly updated.
[`Input`]: https://github.com/postcss/postcss/blob/master/lib/input.es6
### Raw Values
A good PostCSS parser should provide all information (including spaces symbols)
to generate byte-to-byte equal output. It is not so difficult, but respectful
for user input and allow integration smoke tests.
A parser should save all additional symbols to `node.raws` object.
It is an open structure for you, you can add additional keys.
For example, [SCSS parser] saves comment types (`/* */` or `//`)
in `node.raws.inline`.
The default parser cleans CSS values from comments and spaces.
It saves the original value with comments to `node.raws.value.raw` and uses it,
if the node value was not changed.
[SCSS parser]: https://github.com/postcss/postcss-scss
### Tests
Of course, all parsers in the PostCSS ecosystem must have tests.
If your parser just extends CSS syntax (like [SCSS] or [Safe Parser]),
you can use the [PostCSS Parser Tests]. It contains unit & integration tests.
[PostCSS Parser Tests]: https://github.com/postcss/postcss-parser-tests
## Stringifier
A style guide generator is a good example of a stringifier. It generates output
HTML which contains CSS components. For this use case, a parser isn't necessary,
so the package should just contain a stringifier.
The Stringifier API is little bit more complicated, than the parser API.
PostCSS generates a source map, so a stringifier cant just return a string.
It must link every substring with its source node.
A Stringifier is a function which receives [`Root`] node and builder callback.
Then it calls builder with every nodes string and node instance.
```js
module.exports = function (root, builder) {
// Some magic
var string = decl.prop + ':' + decl.value + ';';
builder(string, decl);
// Some science
};
```
### Main Theory
PostCSS [default stringifier] is just a class with a method for each node type
and many methods to detect raw properties.
In most cases it will be enough just to extend this class,
like in [SCSS stringifier].
[default stringifier]: https://github.com/postcss/postcss/blob/master/lib/stringifier.es6
[SCSS stringifier]: https://github.com/postcss/postcss-scss/blob/master/lib/scss-stringifier.es6
### Builder Function
A builder function will be passed to `stringify` function as second argument.
For example, the default PostCSS stringifier class saves it
to `this.builder` property.
Builder receives output substring and source node to append this substring
to the final output.
Some nodes contain other nodes in the middle. For example, a rule has a `{`
at the beginning, many declarations inside and a closing `}`.
For these cases, you should pass a third argument to builder function:
`'start'` or `'end'` string:
```js
this.builder(rule.selector + '{', rule, 'start');
// Stringify declarations inside
this.builder('}', rule, 'end');
```
### Raw Values
A good PostCSS custom syntax saves all symbols and provide byte-to-byte equal
output if there were no changes.
This is why every node has `node.raws` object to store space symbol, etc.
Be careful, because sometimes these raw properties will not be present; some
nodes may be built manually, or may lose their indentation when they are moved
to another parent node.
This is why the default stringifier has a `raw()` method to autodetect raw
properties by other nodes. For example, it will look at other nodes to detect
indent size and them multiply it with the current node depth.
### Tests
A stringifier must have tests too.
You can use unit and integration test cases from [PostCSS Parser Tests].
Just compare input CSS with CSS after your parser and stringifier.
[PostCSS Parser Tests]: https://github.com/postcss/postcss-parser-tests

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,61 @@
'use strict';
exports.__esModule = true;
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Represents a comment between declarations or statements (rule and at-rules).
*
* Comments inside selectors, at-rule parameters, or declaration values
* will be stored in the `raws` properties explained above.
*
* @extends Node
*/
var Comment = function (_Node) {
_inherits(Comment, _Node);
function Comment(defaults) {
_classCallCheck(this, Comment);
var _this = _possibleConstructorReturn(this, _Node.call(this, defaults));
_this.type = 'comment';
return _this;
}
/**
* @memberof Comment#
* @member {string} text - the comments text
*/
/**
* @memberof Comment#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node.
* * `left`: the space symbols between `/*` and the comments text.
* * `right`: the space symbols between the comments text.
*/
return Comment;
}(_node2.default);
exports.default = Comment;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImNvbW1lbnQuZXM2Il0sIm5hbWVzIjpbIkNvbW1lbnQiLCJkZWZhdWx0cyIsInR5cGUiXSwibWFwcGluZ3MiOiI7Ozs7QUFBQTs7Ozs7Ozs7Ozs7O0FBRUE7Ozs7Ozs7O0lBUU1BLE87OztBQUVGLG1CQUFZQyxRQUFaLEVBQXNCO0FBQUE7O0FBQUEsaURBQ2xCLGlCQUFNQSxRQUFOLENBRGtCOztBQUVsQixVQUFLQyxJQUFMLEdBQVksU0FBWjtBQUZrQjtBQUdyQjs7QUFFRDs7Ozs7QUFLQTs7Ozs7Ozs7Ozs7Ozs7Ozs7a0JBY1dGLE8iLCJmaWxlIjoiY29tbWVudC5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBOb2RlI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mVmb3JlIHRoZSBub2RlLlxuICAgICAqICogYGxlZnRgOiB0aGUgc3BhY2Ugc3ltYm9scyBiZXR3ZWVuIGAvKmAgYW5kIHRoZSBjb21tZW504oCZcyB0ZXh0LlxuICAgICAqICogYHJpZ2h0YDogdGhlIHNwYWNlIHN5bWJvbHMgYmV0d2VlbiB0aGUgY29tbWVudOKAmXMgdGV4dC5cbiAgICAgKi9cbn1cblxuZXhwb3J0IGRlZmF1bHQgQ29tbWVudDtcbiJdfQ==

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,101 @@
'use strict';
exports.__esModule = true;
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Represents a CSS declaration.
*
* @extends Node
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.type //=> 'decl'
* decl.toString() //=> ' color: black'
*/
var Declaration = function (_Node) {
_inherits(Declaration, _Node);
function Declaration(defaults) {
_classCallCheck(this, Declaration);
var _this = _possibleConstructorReturn(this, _Node.call(this, defaults));
_this.type = 'decl';
return _this;
}
/**
* @memberof Declaration#
* @member {string} prop - the declarations property name
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.prop //=> 'color'
*/
/**
* @memberof Declaration#
* @member {string} value - the declarations value
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.value //=> 'black'
*/
/**
* @memberof Declaration#
* @member {boolean} important - `true` if the declaration
* has an !important annotation.
*
* @example
* const root = postcss.parse('a { color: black !important; color: red }');
* root.first.first.important //=> true
* root.first.last.important //=> undefined
*/
/**
* @memberof Declaration#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `between`: the symbols between the property and value
* for declarations.
* * `important`: the content of the important statement,
* if it is not just `!important`.
*
* PostCSS cleans declaration from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you dont change a declarations value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '\n ', between: ':' }
*/
return Declaration;
}(_node2.default);
exports.default = Declaration;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImRlY2xhcmF0aW9uLmVzNiJdLCJuYW1lcyI6WyJEZWNsYXJhdGlvbiIsImRlZmF1bHRzIiwidHlwZSJdLCJtYXBwaW5ncyI6Ijs7OztBQUFBOzs7Ozs7Ozs7Ozs7QUFFQTs7Ozs7Ozs7Ozs7SUFXTUEsVzs7O0FBRUYsdUJBQVlDLFFBQVosRUFBc0I7QUFBQTs7QUFBQSxpREFDbEIsaUJBQU1BLFFBQU4sQ0FEa0I7O0FBRWxCLFVBQUtDLElBQUwsR0FBWSxNQUFaO0FBRmtCO0FBR3JCOztBQUVEOzs7Ozs7Ozs7O0FBVUE7Ozs7Ozs7Ozs7QUFVQTs7Ozs7Ozs7Ozs7QUFXQTs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztrQkEyQldGLFciLCJmaWxlIjoiZGVjbGFyYXRpb24uanMiLCJz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Y2Ugc3ltYm9scyBiZWZvcmUgdGhlIG5vZGUuIEl0IGFsc28gc3RvcmVzIGAqYFxuICAgICAqICAgYW5kIGBfYCBzeW1ib2xzIGJlZm9yZSB0aGUgZGVjbGFyYXRpb24gKElFIGhhY2spLlxuICAgICAqICogYGJldHdlZW5gOiB0aGUgc3ltYm9scyBiZXR3ZWVuIHRoZSBwcm9wZXJ0eSBhbmQgdmFsdWVcbiAgICAgKiAgIGZvciBkZWNsYXJhdGlvbnMuXG4gICAgICogKiBgaW1wb3J0YW50YDogdGhlIGNvbnRlbnQgb2YgdGhlIGltcG9ydGFudCBzdGF0ZW1lbnQsXG4gICAgICogICBpZiBpdCBpcyBub3QganVzdCBgIWltcG9ydGFudGAuXG4gICAgICpcbiAgICAgKiBQb3N0Q1NTIGNsZWFucyBkZWNsYXJhdGlvbiBmcm9tIGNvbW1lbnRzIGFuZCBleHRyYSBzcGFjZXMsXG4gICAgICogYnV0IGl0IHN0b3JlcyBvcmlnaW4gY29udGVudCBpbiByYXdzIHByb3BlcnRpZXMuXG4gICAgICogQXMgc3VjaCwgaWYgeW91IGRvbuKAmXQgY2hhbmdlIGEgZGVjbGFyYXRpb27igJlzIHZhbHVlLFxuICAgICAqIFBvc3RDU1Mgd2lsbCB1c2UgdGhlIHJhdyB2YWx1ZSB3aXRoIGNvbW1lbnRzLlxuICAgICAqXG4gICAgICogQGV4YW1wbGVcbiAgICAgKiBjb25zdCByb290ID0gcG9zdGNzcy5wYXJzZSgnYSB7XFxuICBjb2xvcjpibGFja1xcbn0nKVxuICAgICAqIHJvb3QuZmlyc3QuZmlyc3QucmF3cyAvLz0+IHsgYmVmb3JlOiAnXFxuICAnLCBiZXR3ZWVuOiAnOicgfVxuICAgICAqL1xuXG59XG5cbmV4cG9ydCBkZWZhdWx0IERlY2xhcmF0aW9uO1xuIl19

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,41 @@
'use strict';
exports.__esModule = true;
exports.default = parse;
var _parser = require('./parser');
var _parser2 = _interopRequireDefault(_parser);
var _input = require('./input');
var _input2 = _interopRequireDefault(_input);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function parse(css, opts) {
if (opts && opts.safe) {
throw new Error('Option safe was removed. ' + 'Use parser: require("postcss-safe-parser")');
}
var input = new _input2.default(css, opts);
var parser = new _parser2.default(input);
try {
parser.parse();
} catch (e) {
if (e.name === 'CssSyntaxError' && opts && opts.from) {
if (/\.scss$/i.test(opts.from)) {
e.message += '\nYou tried to parse SCSS with ' + 'the standard CSS parser; ' + 'try again with the postcss-scss parser';
} else if (/\.sass/i.test(opts.from)) {
e.message += '\nYou tried to parse Sass with ' + 'the standard CSS parser; ' + 'try again with the postcss-sass parser';
} else if (/\.less$/i.test(opts.from)) {
e.message += '\nYou tried to parse Less with ' + 'the standard CSS parser; ' + 'try again with the postcss-less parser';
}
}
throw e;
}
return parser.root;
}
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInBhcnNlLmVzNiJdLCJuYW1lcyI6WyJwYXJzZSIsImNzcyIsIm9wdHMiLCJzYWZlIiwiRXJyb3IiLCJpbnB1dCIsInBhcnNlciIsImUiLCJuYW1lIiwiZnJvbSIsInRlc3QiLCJtZXNzYWdlIiwicm9vdCJdLCJtYXBwaW5ncyI6Ijs7O2tCQUd3QkEsSzs7QUFIeEI7Ozs7QUFDQTs7Ozs7O0FBRWUsU0FBU0EsS0FBVCxDQUFlQyxHQUFmLEVBQW9CQyxJQUFwQixFQUEwQjtBQUNyQyxRQUFLQSxRQUFRQSxLQUFLQyxJQUFsQixFQUF5QjtBQUNyQixjQUFNLElBQUlDLEtBQUosQ0FBVSw4QkFDQSw0Q0FEVixDQUFOO0FBRUg7O0FBRUQsUUFBSUMsUUFBUSxvQkFBVUosR0FB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gICBlLm1lc3NhZ2UgKz0gJ1xcbllvdSB0cmllZCB0byBwYXJzZSBMZXNzIHdpdGggJyArXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICd0aGUgc3RhbmRhcmQgQ1NTIHBhcnNlcjsgJyArXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICd0cnkgYWdhaW4gd2l0aCB0aGUgcG9zdGNzcy1sZXNzIHBhcnNlcic7XG4gICAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgICAgdGhyb3cgZTtcbiAgICB9XG5cbiAgICByZXR1cm4gcGFyc2VyLnJvb3Q7XG59XG4iXX0=

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,123 @@
'use strict';
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _container = require('./container');
var _container2 = _interopRequireDefault(_container);
var _list = require('./list');
var _list2 = _interopRequireDefault(_list);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Represents a CSS rule: a selector followed by a declaration block.
*
* @extends Container
*
* @example
* const root = postcss.parse('a{}');
* const rule = root.first;
* rule.type //=> 'rule'
* rule.toString() //=> 'a{}'
*/
var Rule = function (_Container) {
_inherits(Rule, _Container);
function Rule(defaults) {
_classCallCheck(this, Rule);
var _this = _possibleConstructorReturn(this, _Container.call(this, defaults));
_this.type = 'rule';
if (!_this.nodes) _this.nodes = [];
return _this;
}
/**
* An array containing the rules individual selectors.
* Groups of selectors are split at commas.
*
* @type {string[]}
*
* @example
* const root = postcss.parse('a, b { }');
* const rule = root.first;
*
* rule.selector //=> 'a, b'
* rule.selectors //=> ['a', 'b']
*
* rule.selectors = ['a', 'strong'];
* rule.selector //=> 'a, strong'
*/
_createClass(Rule, [{
key: 'selectors',
get: function get() {
return _list2.default.comma(this.selector);
},
set: function set(values) {
var match = this.selector ? this.selector.match(/,\s*/) : null;
var sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen');
this.selector = values.join(sep);
}
/**
* @memberof Rule#
* @member {string} selector - the rules full selector represented
* as a string
*
* @example
* const root = postcss.parse('a, b { }');
* const rule = root.first;
* rule.selector //=> 'a, b'
*/
/**
* @memberof Rule#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains `true` if the last child has
* an (optional) semicolon.
* * `ownSemicolon`: contains `true` if there is semicolon after rule.
*
* PostCSS cleans selectors from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you dont change a declarations value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '', between: ' ', after: '\n' }
*/
}]);
return Rule;
}(_container2.default);
exports.default = Rule;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInJ1bGUuZXM2Il0sIm5hbWVzIjpbIlJ1bGUiLCJkZWZhdWx0cyIsInR5cGUiLCJub2RlcyIsImNvbW1hIiwic2VsZWN0b3IiLCJ2YWx1ZXMiLCJtYXRjaCIsInNlcCIsInJhdyIsImpvaW4iXSwibWFwcGluZ3MiOiI7Ozs7OztBQUFBOzs7O0FBQ0E7Ozs7Ozs7Ozs7OztBQUVBOzs7Ozs7Ozs7OztJQVdNQSxJOzs7QUFFRixnQkFBWUMsUUFBWixFQUFzQjtBQUFBOztBQUFBLGlEQUNsQixzQkFBTUEsUUFBTixDQURrQjs7QUFFbEIsVUFBS0MsSUFBTCxHQUFZLE1BQVo7QUFDQSxRQUFLLENBQUMsTUFBS0MsS0FBWCxFQUFtQixNQUFLQSxLQUFMLEdBQWEsRUFBYjtBQUhEO0FBSXJCOztBQUVEOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozt3QkFnQmdCO0FBQ1osYUFBTyxlQUFLQyxLQUFMLENBQVcsS0FBS0MsUUFBaEIsQ0FBUDtBQUNILEs7c0JBRWFDLE0sRUFBUTtBQUNsQixVQUFJQyxRQUFRLEtBQUtGLFFBQUwsR0FBZ0IsS0FBS0EsUUFBTCxDQUFjRSxLQUFkLENBQW9CLE1BQXBCLENBQWhCLEdBQThDLElBQTFEO0FBQ0EsVUFBSUMsTUFBUUQsUUFBUUEsTUFBTSxDQUFOLENBQVIsR0FBbUIsTUFBTSxLQUFLRSxHQUFMLENBQVMsU0FBVCxFQUFvQixZQUFwQixDQUFyQztBQUNBLFdBQUtKLFFBQUwsR0FBZ0JDLE9BQU9JLElBQVAsQ0FBWUYsR0FBWixDQUFoQjtBQUNIO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xvbi5cbiAgICAgKiAqIGBvd25TZW1pY29sb25gOiBjb250YWlucyBgdHJ1ZWAgaWYgdGhlcmUgaXMgc2VtaWNvbG9uIGFmdGVyIHJ1bGUuXG4gICAgICpcbiAgICAgKiBQb3N0Q1NTIGNsZWFucyBzZWxlY3RvcnMgZnJvbSBjb21tZW50cyBhbmQgZXh0cmEgc3BhY2VzLFxuICAgICAqIGJ1dCBpdCBzdG9yZXMgb3JpZ2luIGNvbnRlbnQgaW4gcmF3cyBwcm9wZXJ0aWVzLlxuICAgICAqIEFzIHN1Y2gsIGlmIHlvdSBkb27igJl0IGNoYW5nZSBhIGRlY2xhcmF0aW9u4oCZcyB2YWx1ZSxcbiAgICAgKiBQb3N0Q1NTIHdpbGwgdXNlIHRoZSByYXcgdmFsdWUgd2l0aCBjb21tZW50cy5cbiAgICAgKlxuICAgICAqIEBleGFtcGxlXG4gICAgICogY29uc3Qgcm9vdCA9IHBvc3Rjc3MucGFyc2UoJ2Ege1xcbiAgY29sb3I6YmxhY2tcXG59JylcbiAgICAgKiByb290LmZpcnN0LmZpcnN0LnJhd3MgLy89PiB7IGJlZm9yZTogJycsIGJldHdlZW46ICcgJywgYWZ0ZXI6ICdcXG4nIH1cbiAgICAgKi9cblxufVxuXG5leHBvcnQgZGVmYXVsdCBSdWxlO1xuIl19

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,17 @@
'use strict';
exports.__esModule = true;
exports.default = stringify;
var _stringifier = require('./stringifier');
var _stringifier2 = _interopRequireDefault(_stringifier);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function stringify(node, builder) {
var str = new _stringifier2.default(builder);
str.stringify(node);
}
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInN0cmluZ2lmeS5lczYiXSwibmFtZXMiOlsic3RyaW5naWZ5Iiwibm9kZSIsImJ1aWxkZXIiLCJzdHIiXSwibWFwcGluZ3MiOiI7OztrQkFFd0JBLFM7O0FBRnhCOzs7Ozs7QUFFZSxTQUFTQSxTQUFULENBQW1CQyxJQUFuQixFQUF5QkMsT0FBekIsRUFBa0M7QUFDN0MsUUFBSUMsTUFBTSwwQkFBZ0JELE9BQWhCLENBQVY7QUFDQUMsUUFBSUgsU0FBSixDQUFjQyxJQUFkO0FBQ0giLCJmaWxlIjoic3RyaW5naWZ5LmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IFN0cmluZ2lmaWVyIGZyb20gJy4vc3RyaW5naWZpZXInO1xuXG5leHBvcnQgZGVmYXVsdCBmdW5jdGlvbiBzdHJpbmdpZnkobm9kZSwgYnVpbGRlcikge1xuICAgIGxldCBzdHIgPSBuZXcgU3RyaW5naWZpZXIoYnVpbGRlcik7XG4gICAgc3RyLnN0cmluZ2lmeShub2RlKTtcbn1cbiJdfQ==

View File

@@ -0,0 +1,83 @@
'use strict';
exports.__esModule = true;
var _chalk = require('chalk');
var _chalk2 = _interopRequireDefault(_chalk);
var _tokenize = require('./tokenize');
var _tokenize2 = _interopRequireDefault(_tokenize);
var _input = require('./input');
var _input2 = _interopRequireDefault(_input);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var HIGHLIGHT_THEME = {
'brackets': _chalk2.default.cyan,
'at-word': _chalk2.default.cyan,
'call': _chalk2.default.cyan,
'comment': _chalk2.default.gray,
'string': _chalk2.default.green,
'class': _chalk2.default.yellow,
'hash': _chalk2.default.magenta,
'(': _chalk2.default.cyan,
')': _chalk2.default.cyan,
'{': _chalk2.default.yellow,
'}': _chalk2.default.yellow,
'[': _chalk2.default.yellow,
']': _chalk2.default.yellow,
':': _chalk2.default.yellow,
';': _chalk2.default.yellow
};
function getTokenType(_ref, processor) {
var type = _ref[0],
value = _ref[1];
if (type === 'word') {
if (value[0] === '.') {
return 'class';
}
if (value[0] === '#') {
return 'hash';
}
}
if (!processor.endOfFile()) {
var next = processor.nextToken();
processor.back(next);
if (next[0] === 'brackets' || next[0] === '(') return 'call';
}
return type;
}
function terminalHighlight(css) {
var processor = (0, _tokenize2.default)(new _input2.default(css), { ignoreErrors: true });
var result = '';
var _loop = function _loop() {
var token = processor.nextToken();
var color = HIGHLIGHT_THEME[getTokenType(token, processor)];
if (color) {
result += token[1].split(/\r?\n/).map(function (i) {
return color(i);
}).join('\n');
} else {
result += token[1];
}
};
while (!processor.endOfFile()) {
_loop();
}
return result;
}
exports.default = terminalHighlight;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInRlcm1pbmFsLWhpZ2hsaWdodC5lczYiXSwibmFtZXMiOlsiSElHSExJR0hUX1RIRU1FIiwiY3lhbiIsImdyYXkiLCJncmVlbiIsInllbGxvdyIsIm1hZ2VudGEiLCJnZXRUb2tlblR5cGUiLCJwcm9jZXNzb3IiLCJ0eXBlIiwidmFsdWUiLCJlbmRPZkZpbGUiLCJuZXh0IiwibmV4dFRva2VuIiwiYmFjayIsInRlcm1pbmFsSGlnaGxpZ2h0IiwiY3NzIiwiaWdub3JlRXJyb3JzIiwicmVzdWx0IiwidG9rZW4iLCJjb2xvciIsInNwbGl0IiwibWFwIiwiaSIsImpvaW4iXSwibWFwcGluZ3MiOiI7Ozs7QUFBQTs7OztBQUVBOzs7O0FBQ0E7Ozs7OztBQUVBLElBQU1BLGtCQUFrQjtBQUNwQixnQkFBWSxnQkFBTUMsSUFERTtBQUVwQixlQUFZLGdCQUFNQSxJQUZFO0FBR3BCLFlBQVksZ0JBQU1BLElBSEU7QUFJcEIsZUFBWSxnQkFBTUMsSUFKRTtBQUtwQixjQUFZLGdCQUFNQyxLQUxFO0FBTXBCLGFBQVksZ0JBQU1DLE1BTkU7QUFPcEIsWUFBWSxnQkFBTUMsT0FQRTtBQVFwQixTQUFZLGdCQUFNSixJQVJFO0FBU3BCLFNBQVksZ0JBQU1BLElBVEU7QUFVcEIsU0FBWSxnQkFBTUcs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jaGFsay55ZWxsb3csXG4gICAgJ10nOiAgICAgICAgY2hhbGsueWVsbG93LFxuICAgICc6JzogICAgICAgIGNoYWxrLnllbGxvdyxcbiAgICAnOyc6ICAgICAgICBjaGFsay55ZWxsb3dcbn07XG5cbmZ1bmN0aW9uIGdldFRva2VuVHlwZShbdHlwZSwgdmFsdWVdLCBwcm9jZXNzb3IpIHtcbiAgICBpZiAoIHR5cGUgPT09ICd3b3JkJyApIHtcbiAgICAgICAgaWYgKCB2YWx1ZVswXSA9PT0gJy4nICkge1xuICAgICAgICAgICAgcmV0dXJuICdjbGFzcyc7XG4gICAgICAgIH1cbiAgICAgICAgaWYgKCB2YWx1ZVswXSA9PT0gJyMnICkge1xuICAgICAgICAgICAgcmV0dXJuICdoYXNoJztcbiAgICAgICAgfVxuICAgIH1cblxuICAgIGlmICggIXByb2Nlc3Nvci5lbmRPZkZpbGUoKSApIHtcbiAgICAgICAgbGV0IG5leHQgPSBwcm9jZXNzb3IubmV4dFRva2VuKCk7XG4gICAgICAgIHByb2Nlc3Nvci5iYWNrKG5leHQpO1xuICAgICAgICBpZiAoIG5leHRbMF0gPT09ICdicmFja2V0cycgfHwgbmV4dFswXSA9PT0gJygnICkgcmV0dXJuICdjYWxsJztcbiAgICB9XG5cbiAgICByZXR1cm4gdHlwZTtcbn1cblxuZnVuY3Rpb24gdGVybWluYWxIaWdobGlnaHQoY3NzKSB7XG4gICAgbGV0IHByb2Nlc3NvciA9IHRva2VuaXplcihuZXcgSW5wdXQoY3NzKSwgeyBpZ25vcmVFcnJvcnM6IHRydWUgfSk7XG4gICAgbGV0IHJlc3VsdCA9ICcnO1xuICAgIHdoaWxlICggIXByb2Nlc3Nvci5lbmRPZkZpbGUoKSApIHtcbiAgICAgICAgbGV0IHRva2VuID0gcHJvY2Vzc29yLm5leHRUb2tlbigpO1xuICAgICAgICBsZXQgY29sb3IgPSBISUdITElHSFRfVEhFTUVbZ2V0VG9rZW5UeXBlKHRva2VuLCBwcm9jZXNzb3IpXTtcbiAgICAgICAgaWYgKCBjb2xvciApIHtcbiAgICAgICAgICAgIHJlc3VsdCArPSB0b2tlblsxXS5zcGxpdCgvXFxyP1xcbi8pXG4gICAgICAgICAgICAgICAgLm1hcCggaSA9PiBjb2xvcihpKSApXG4gICAgICAgICAgICAgICAgLmpvaW4oJ1xcbicpO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgcmVzdWx0ICs9IHRva2VuWzFdO1xuICAgICAgICB9XG4gICAgfVxuICAgIHJldHVybiByZXN1bHQ7XG59XG5cbmV4cG9ydCBkZWZhdWx0IHRlcm1pbmFsSGlnaGxpZ2h0O1xuIl19

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,52 @@
'use strict';
exports.__esModule = true;
/**
* Contains helpers for working with vendor prefixes.
*
* @example
* const vendor = postcss.vendor;
*
* @namespace vendor
*/
var vendor = {
/**
* Returns the vendor prefix extracted from an input string.
*
* @param {string} prop - string with or without vendor prefix
*
* @return {string} vendor prefix or empty string
*
* @example
* postcss.vendor.prefix('-moz-tab-size') //=> '-moz-'
* postcss.vendor.prefix('tab-size') //=> ''
*/
prefix: function prefix(prop) {
var match = prop.match(/^(-\w+-)/);
if (match) {
return match[0];
} else {
return '';
}
},
/**
* Returns the input string stripped of its vendor prefix.
*
* @param {string} prop - string with or without vendor prefix
*
* @return {string} string name without vendor prefixes
*
* @example
* postcss.vendor.unprefixed('-moz-tab-size') //=> 'tab-size'
*/
unprefixed: function unprefixed(prop) {
return prop.replace(/^-\w+-/, '');
}
};
exports.default = vendor;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInZlbmRvci5lczYiXSwibmFtZXMiOlsidmVuZG9yIiwicHJlZml4IiwicHJvcCIsIm1hdGNoIiwidW5wcmVmaXhlZCIsInJlcGxhY2UiXSwibWFwcGluZ3MiOiI7OztBQUFBOzs7Ozs7OztBQVFBLElBQUlBLFNBQVM7O0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Nzcy52ZW5kb3IucHJlZml4KCd0YWItc2l6ZScpICAgICAgLy89PiAnJ1xuICAgICAqL1xuICAgIHByZWZpeChwcm9wKSB7XG4gICAgICAgIGxldCBtYXRjaCA9IHByb3AubWF0Y2goL14oLVxcdystKS8pO1xuICAgICAgICBpZiAoIG1hdGNoICkge1xuICAgICAgICAgICAgcmV0dXJuIG1hdGNoWzBdO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgcmV0dXJuICcnO1xuICAgICAgICB9XG4gICAgfSxcblxuICAgIC8qKlxuICAgICAqIFJldHVybnMgdGhlIGlucHV0IHN0cmluZyBzdHJpcHBlZCBvZiBpdHMgdmVuZG9yIHByZWZpeC5cbiAgICAgKlxuICAgICAqIEBwYXJhbSB7c3RyaW5nfSBwcm9wIC0gc3RyaW5nIHdpdGggb3Igd2l0aG91dCB2ZW5kb3IgcHJlZml4XG4gICAgICpcbiAgICAgKiBAcmV0dXJuIHtzdHJpbmd9IHN0cmluZyBuYW1lIHdpdGhvdXQgdmVuZG9yIHByZWZpeGVzXG4gICAgICpcbiAgICAgKiBAZXhhbXBsZVxuICAgICAqIHBvc3Rjc3MudmVuZG9yLnVucHJlZml4ZWQoJy1tb3otdGFiLXNpemUnKSAvLz0+ICd0YWItc2l6ZSdcbiAgICAgKi9cbiAgICB1bnByZWZpeGVkKHByb3ApIHtcbiAgICAgICAgcmV0dXJuIHByb3AucmVwbGFjZSgvXi1cXHcrLS8sICcnKTtcbiAgICB9XG5cbn07XG5cbmV4cG9ydCBkZWZhdWx0IHZlbmRvcjtcbiJdfQ==

View File

@@ -0,0 +1,14 @@
'use strict';
exports.__esModule = true;
exports.default = warnOnce;
var printed = {};
function warnOnce(message) {
if (printed[message]) return;
printed[message] = true;
if (typeof console !== 'undefined' && console.warn) console.warn(message);
}
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndhcm4tb25jZS5lczYiXSwibmFtZXMiOlsid2Fybk9uY2UiLCJwcmludGVkIiwibWVzc2FnZSIsImNvbnNvbGUiLCJ3YXJuIl0sIm1hcHBpbmdzIjoiOzs7a0JBRXdCQSxRO0FBRnhCLElBQUlDLFVBQVUsRUFBZDs7QUFFZSxTQUFTRCxRQUFULENBQWtCRSxPQUFsQixFQUEyQjtBQUN0QyxRQUFLRCxRQUFRQyxPQUFSLENBQUwsRUFBd0I7QUFDeEJELFlBQVFDLE9BQVIsSUFBbUIsSUFBbkI7O0FBRUEsUUFBSyxPQUFPQyxPQUFQLEtBQW1CLFdBQW5CLElBQWtDQSxRQUFRQyxJQUEvQyxFQUFzREQsUUFBUUMsSUFBUixDQUFhRixPQUFiO0FBQ3pEIiwiZmlsZSI6Indhcm4tb25jZS5qcyIsInNvdXJjZXNDb250ZW50IjpbImxldCBwcmludGVkID0geyB9O1xuXG5leHBvcnQgZGVmYXVsdCBmdW5jdGlvbiB3YXJuT25jZShtZXNzYWdlKSB7XG4gICAgaWYgKCBwcmludGVkW21lc3NhZ2VdICkgcmV0dXJuO1xuICAgIHByaW50ZWRbbWVzc2FnZV0gPSB0cnVlO1xuXG4gICAgaWYgKCB0eXBlb2YgY29uc29sZSAhPT0gJ3VuZGVmaW5lZCcgJiYgY29uc29sZS53YXJuICkgY29uc29sZS53YXJuKG1lc3NhZ2UpO1xufVxuIl19

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,228 @@
'use strict';
const escapeStringRegexp = require('escape-string-regexp');
const ansiStyles = require('ansi-styles');
const supportsColor = require('supports-color');
const template = require('./templates.js');
const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');
// `supportsColor.level` → `ansiStyles.color[name]` mapping
const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
// `color-convert` models to exclude from the Chalk API due to conflicts and such
const skipModels = new Set(['gray']);
const styles = Object.create(null);
function applyOptions(obj, options) {
options = options || {};
// Detect level if not set manually
const scLevel = supportsColor ? supportsColor.level : 0;
obj.level = options.level === undefined ? scLevel : options.level;
obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
}
function Chalk(options) {
// We check for this.template here since calling `chalk.constructor()`
// by itself will have a `this` of a previously constructed chalk object
if (!this || !(this instanceof Chalk) || this.template) {
const chalk = {};
applyOptions(chalk, options);
chalk.template = function () {
const args = [].slice.call(arguments);
return chalkTag.apply(null, [chalk.template].concat(args));
};
Object.setPrototypeOf(chalk, Chalk.prototype);
Object.setPrototypeOf(chalk.template, chalk);
chalk.template.constructor = Chalk;
return chalk.template;
}
applyOptions(this, options);
}
// Use bright blue on Windows as the normal blue color is illegible
if (isSimpleWindowsTerm) {
ansiStyles.blue.open = '\u001B[94m';
}
for (const key of Object.keys(ansiStyles)) {
ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
styles[key] = {
get() {
const codes = ansiStyles[key];
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
}
};
}
styles.visible = {
get() {
return build.call(this, this._styles || [], true, 'visible');
}
};
ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
for (const model of Object.keys(ansiStyles.color.ansi)) {
if (skipModels.has(model)) {
continue;
}
styles[model] = {
get() {
const level = this.level;
return function () {
const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
const codes = {
open,
close: ansiStyles.color.close,
closeRe: ansiStyles.color.closeRe
};
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
};
}
};
}
ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
if (skipModels.has(model)) {
continue;
}
const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
styles[bgModel] = {
get() {
const level = this.level;
return function () {
const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
const codes = {
open,
close: ansiStyles.bgColor.close,
closeRe: ansiStyles.bgColor.closeRe
};
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
};
}
};
}
const proto = Object.defineProperties(() => {}, styles);
function build(_styles, _empty, key) {
const builder = function () {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
builder._empty = _empty;
const self = this;
Object.defineProperty(builder, 'level', {
enumerable: true,
get() {
return self.level;
},
set(level) {
self.level = level;
}
});
Object.defineProperty(builder, 'enabled', {
enumerable: true,
get() {
return self.enabled;
},
set(enabled) {
self.enabled = enabled;
}
});
// See below for fix regarding invisible grey/dim combination on Windows
builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';
// `__proto__` is used because we must return a function, but there is
// no way to create a function with a different prototype
builder.__proto__ = proto; // eslint-disable-line no-proto
return builder;
}
function applyStyle() {
// Support varags, but simply cast to string in case there's only one arg
const args = arguments;
const argsLen = args.length;
let str = String(arguments[0]);
if (argsLen === 0) {
return '';
}
if (argsLen > 1) {
// Don't slice `arguments`, it prevents V8 optimizations
for (let a = 1; a < argsLen; a++) {
str += ' ' + args[a];
}
}
if (!this.enabled || this.level <= 0 || !str) {
return this._empty ? '' : str;
}
// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
// see https://github.com/chalk/chalk/issues/58
// If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
const originalDim = ansiStyles.dim.open;
if (isSimpleWindowsTerm && this.hasGrey) {
ansiStyles.dim.open = '';
}
for (const code of this._styles.slice().reverse()) {
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
str = code.open + str.replace(code.closeRe, code.open) + code.close;
// Close the styling before a linebreak and reopen
// after next line to fix a bleed issue on macOS
// https://github.com/chalk/chalk/pull/92
str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
}
// Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
ansiStyles.dim.open = originalDim;
return str;
}
function chalkTag(chalk, strings) {
if (!Array.isArray(strings)) {
// If chalk() was called by itself or with a string,
// return the string itself as a string.
return [].slice.call(arguments, 1).join(' ');
}
const args = [].slice.call(arguments, 2);
const parts = [strings.raw[0]];
for (let i = 1; i < strings.length; i++) {
parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
parts.push(String(strings.raw[i]));
}
return template(chalk, parts.join(''));
}
Object.defineProperties(Chalk.prototype, styles);
module.exports = Chalk(); // eslint-disable-line new-cap
module.exports.supportsColor = supportsColor;
module.exports.default = module.exports; // For TypeScript

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,101 @@
{
"_args": [
[
"chalk@2.3.0",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "chalk@2.3.0",
"_id": "chalk@2.3.0",
"_inBundle": false,
"_integrity": "sha512-Az5zJR2CBujap2rqXGaJKaPHyJ0IrUimvYNX+ncCy8PJP4ltOGTrHUIo097ZaL2zMeKYpiCdqDvS6zdrTFok3Q==",
"_location": "/react-scripts/postcss/chalk",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "chalk@2.3.0",
"name": "chalk",
"escapedName": "chalk",
"rawSpec": "2.3.0",
"saveSpec": null,
"fetchSpec": "2.3.0"
},
"_requiredBy": [
"/react-scripts/postcss"
],
"_resolved": "https://registry.npmjs.org/chalk/-/chalk-2.3.0.tgz",
"_spec": "2.3.0",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"bugs": {
"url": "https://github.com/chalk/chalk/issues"
},
"dependencies": {
"ansi-styles": "^3.1.0",
"escape-string-regexp": "^1.0.5",
"supports-color": "^4.0.0"
},
"description": "Terminal string styling done right",
"devDependencies": {
"ava": "*",
"coveralls": "^3.0.0",
"execa": "^0.8.0",
"import-fresh": "^2.0.0",
"matcha": "^0.7.0",
"nyc": "^11.0.2",
"resolve-from": "^4.0.0",
"typescript": "^2.5.3",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js",
"templates.js",
"types/index.d.ts"
],
"homepage": "https://github.com/chalk/chalk#readme",
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"str",
"ansi",
"style",
"styles",
"tty",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"license": "MIT",
"name": "chalk",
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/chalk.git"
},
"scripts": {
"bench": "matcha benchmark.js",
"coveralls": "nyc report --reporter=text-lcov | coveralls",
"test": "xo && tsc --project types && nyc ava"
},
"types": "types/index.d.ts",
"version": "2.3.0",
"xo": {
"envs": [
"node",
"mocha"
]
}
}

View File

@@ -0,0 +1,309 @@
<h1 align="center">
<br>
<br>
<img width="320" src="https://cdn.rawgit.com/chalk/chalk/19935d6484811c5e468817f846b7b3d417d7bf4a/logo.svg" alt="chalk">
<br>
<br>
<br>
</h1>
> Terminal string styling done right
[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo) [![Mentioned in Awesome Node.js](https://awesome.re/mentioned-badge.svg)](https://github.com/sindresorhus/awesome-nodejs)
### [See what's new in Chalk 2](https://github.com/chalk/chalk/releases/tag/v2.0.0)
![](https://github.com/chalk/ansi-styles/raw/master/screenshot.png)
## Highlights
- Expressive API
- Highly performant
- Ability to nest styles
- [256/Truecolor color support](#256-and-truecolor-color-support)
- Auto-detects color support
- Doesn't extend `String.prototype`
- Clean and focused
- Actively maintained
- [Used by ~17,000 packages](https://www.npmjs.com/browse/depended/chalk) as of June 20th, 2017
## Install
```console
$ npm install chalk
```
## Usage
```js
const chalk = require('chalk');
console.log(chalk.blue('Hello world!'));
```
Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
```js
const chalk = require('chalk');
const log = console.log;
// Combine styled and normal strings
log(chalk.blue('Hello') + 'World' + chalk.red('!'));
// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));
// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
// Nest styles of the same type even (color, underline, background)
log(chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
));
// ES2015 template literal
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);
// ES2015 tagged template literal
log(chalk`
CPU: {red ${cpu.totalPercent}%}
RAM: {green ${ram.used / ram.total * 100}%}
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
`);
// Use RGB colors in terminal emulators that support it.
log(chalk.keyword('orange')('Yay for orange colored text!'));
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));
```
Easily define your own themes:
```js
const chalk = require('chalk');
const error = chalk.bold.red;
const warning = chalk.keyword('orange');
console.log(error('Error!'));
console.log(warning('Warning!'));
```
Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):
```js
const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> 'Hello Sindre'
```
## API
### chalk.`<style>[.<style>...](string, [string...])`
Example: `chalk.red.bold.underline('Hello', 'world');`
Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
Multiple arguments will be separated by space.
### chalk.enabled
Color support is automatically detected, as is the level (see `chalk.level`). However, if you'd like to simply enable/disable Chalk, you can do so via the `.enabled` property.
Chalk is enabled by default unless expicitly disabled via the constructor or `chalk.level` is `0`.
If you need to change this in a reusable module, create a new instance:
```js
const ctx = new chalk.constructor({enabled: false});
```
### chalk.level
Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers.
If you need to change this in a reusable module, create a new instance:
```js
const ctx = new chalk.constructor({level: 0});
```
Levels are as follows:
0. All colors disabled
1. Basic color support (16 colors)
2. 256 color support
3. Truecolor support (16 million colors)
### chalk.supportsColor
Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add the environment variable `FORCE_COLOR=1` to forcefully enable color or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
## Styles
### Modifiers
- `reset`
- `bold`
- `dim`
- `italic` *(Not widely supported)*
- `underline`
- `inverse`
- `hidden`
- `strikethrough` *(Not widely supported)*
- `visible` (Text is emitted only if enabled)
### Colors
- `black`
- `red`
- `green`
- `yellow`
- `blue` *(On Windows the bright version is used since normal blue is illegible)*
- `magenta`
- `cyan`
- `white`
- `gray` ("bright black")
- `redBright`
- `greenBright`
- `yellowBright`
- `blueBright`
- `magentaBright`
- `cyanBright`
- `whiteBright`
### Background colors
- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
- `bgBlackBright`
- `bgRedBright`
- `bgGreenBright`
- `bgYellowBright`
- `bgBlueBright`
- `bgMagentaBright`
- `bgCyanBright`
- `bgWhiteBright`
## Tagged template literal
Chalk can be used as a [tagged template literal](http://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).
```js
const chalk = require('chalk');
const miles = 18;
const calculateFeet = miles => miles * 5280;
console.log(chalk`
There are {bold 5280 feet} in a mile.
In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
`);
```
Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`).
Template styles are chained exactly like normal Chalk styles. The following two statements are equivalent:
```js
console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
console.log(chalk`{bold.rgb(10,100,200) Hello!}`);
```
Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters.
All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.
## 256 and Truecolor color support
Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps.
Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).
Examples:
- `chalk.hex('#DEADED').underline('Hello, world!')`
- `chalk.keyword('orange')('Some orange text')`
- `chalk.rgb(15, 100, 204).inverse('Hello!')`
Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors).
- `chalk.bgHex('#DEADED').underline('Hello, world!')`
- `chalk.bgKeyword('orange')('Some orange text')`
- `chalk.bgRgb(15, 100, 204).inverse('Hello!')`
The following color models can be used:
- [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')`
- [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')`
- [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')`
- [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')`
- [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 1, 1).bold('Orange!')`
- [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hsl(32, 0, 50).bold('Orange!')`
- `ansi16`
- `ansi256`
## Windows
If you're on Windows, do yourself a favor and use [`cmder`](http://cmder.net/) instead of `cmd.exe`.
## Origin story
[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.
## Related
- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal
- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings
- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)
## License
MIT

View File

@@ -0,0 +1,128 @@
'use strict';
const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
const ESCAPES = new Map([
['n', '\n'],
['r', '\r'],
['t', '\t'],
['b', '\b'],
['f', '\f'],
['v', '\v'],
['0', '\0'],
['\\', '\\'],
['e', '\u001B'],
['a', '\u0007']
]);
function unescape(c) {
if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
return String.fromCharCode(parseInt(c.slice(1), 16));
}
return ESCAPES.get(c) || c;
}
function parseArguments(name, args) {
const results = [];
const chunks = args.trim().split(/\s*,\s*/g);
let matches;
for (const chunk of chunks) {
if (!isNaN(chunk)) {
results.push(Number(chunk));
} else if ((matches = chunk.match(STRING_REGEX))) {
results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
} else {
throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
}
}
return results;
}
function parseStyle(style) {
STYLE_REGEX.lastIndex = 0;
const results = [];
let matches;
while ((matches = STYLE_REGEX.exec(style)) !== null) {
const name = matches[1];
if (matches[2]) {
const args = parseArguments(name, matches[2]);
results.push([name].concat(args));
} else {
results.push([name]);
}
}
return results;
}
function buildStyle(chalk, styles) {
const enabled = {};
for (const layer of styles) {
for (const style of layer.styles) {
enabled[style[0]] = layer.inverse ? null : style.slice(1);
}
}
let current = chalk;
for (const styleName of Object.keys(enabled)) {
if (Array.isArray(enabled[styleName])) {
if (!(styleName in current)) {
throw new Error(`Unknown Chalk style: ${styleName}`);
}
if (enabled[styleName].length > 0) {
current = current[styleName].apply(current, enabled[styleName]);
} else {
current = current[styleName];
}
}
}
return current;
}
module.exports = (chalk, tmp) => {
const styles = [];
const chunks = [];
let chunk = [];
// eslint-disable-next-line max-params
tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
if (escapeChar) {
chunk.push(unescape(escapeChar));
} else if (style) {
const str = chunk.join('');
chunk = [];
chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
styles.push({inverse, styles: parseStyle(style)});
} else if (close) {
if (styles.length === 0) {
throw new Error('Found extraneous } in Chalk template literal');
}
chunks.push(buildStyle(chalk, styles)(chunk.join('')));
chunk = [];
styles.pop();
} else {
chunk.push(chr);
}
});
chunks.push(chunk.join(''));
if (styles.length > 0) {
const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
throw new Error(errMsg);
}
return chunks.join('');
};

View File

@@ -0,0 +1,97 @@
// Type definitions for Chalk
// Definitions by: Thomas Sauer <https://github.com/t-sauer>
export const enum Level {
None = 0,
Basic = 1,
Ansi256 = 2,
TrueColor = 3
}
export interface ChalkOptions {
enabled?: boolean;
level?: Level;
}
export interface ChalkConstructor {
new (options?: ChalkOptions): Chalk;
(options?: ChalkOptions): Chalk;
}
export interface ColorSupport {
level: Level;
hasBasic: boolean;
has256: boolean;
has16m: boolean;
}
export interface Chalk {
(...text: string[]): string;
(text: TemplateStringsArray, ...placeholders: string[]): string;
constructor: ChalkConstructor;
enabled: boolean;
level: Level;
rgb(r: number, g: number, b: number): this;
hsl(h: number, s: number, l: number): this;
hsv(h: number, s: number, v: number): this;
hwb(h: number, w: number, b: number): this;
bgHex(color: string): this;
bgKeyword(color: string): this;
bgRgb(r: number, g: number, b: number): this;
bgHsl(h: number, s: number, l: number): this;
bgHsv(h: number, s: number, v: number): this;
bgHwb(h: number, w: number, b: number): this;
hex(color: string): this;
keyword(color: string): this;
readonly reset: this;
readonly bold: this;
readonly dim: this;
readonly italic: this;
readonly underline: this;
readonly inverse: this;
readonly hidden: this;
readonly strikethrough: this;
readonly visible: this;
readonly black: this;
readonly red: this;
readonly green: this;
readonly yellow: this;
readonly blue: this;
readonly magenta: this;
readonly cyan: this;
readonly white: this;
readonly gray: this;
readonly grey: this;
readonly blackBright: this;
readonly redBright: this;
readonly greenBright: this;
readonly yellowBright: this;
readonly blueBright: this;
readonly magentaBright: this;
readonly cyanBright: this;
readonly whiteBright: this;
readonly bgBlack: this;
readonly bgRed: this;
readonly bgGreen: this;
readonly bgYellow: this;
readonly bgBlue: this;
readonly bgMagenta: this;
readonly bgCyan: this;
readonly bgWhite: this;
readonly bgBlackBright: this;
readonly bgRedBright: this;
readonly bgGreenBright: this;
readonly bgYellowBright: this;
readonly bgBlueBright: this;
readonly bgMagentaBright: this;
readonly bgCyanBright: this;
readonly bgWhiteBright: this;
}
declare const chalk: Chalk & { supportsColor: ColorSupport };
export default chalk

View File

@@ -0,0 +1,149 @@
{
"_args": [
[
"postcss@6.0.14",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "postcss@6.0.14",
"_id": "postcss@6.0.14",
"_inBundle": false,
"_integrity": "sha512-NJ1z0f+1offCgadPhz+DvGm5Mkci+mmV5BqD13S992o0Xk9eElxUfPPF+t2ksH5R/17gz4xVK8KWocUQ5o3Rog==",
"_location": "/react-scripts/postcss",
"_phantomChildren": {
"ansi-styles": "3.2.0",
"escape-string-regexp": "1.0.5",
"supports-color": "4.5.0"
},
"_requested": {
"type": "version",
"registry": true,
"raw": "postcss@6.0.14",
"name": "postcss",
"escapedName": "postcss",
"rawSpec": "6.0.14",
"saveSpec": null,
"fetchSpec": "6.0.14"
},
"_requiredBy": [
"/react-scripts/autoprefixer",
"/react-scripts/icss-utils",
"/react-scripts/postcss-flexbugs-fixes",
"/react-scripts/postcss-loader",
"/react-scripts/postcss-modules-extract-imports",
"/react-scripts/postcss-modules-local-by-default",
"/react-scripts/postcss-modules-scope",
"/react-scripts/postcss-modules-values"
],
"_resolved": "https://registry.npmjs.org/postcss/-/postcss-6.0.14.tgz",
"_spec": "6.0.14",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Andrey Sitnik",
"email": "andrey@sitnik.ru"
},
"browser": {
"supports-color": false,
"chalk": false,
"fs": false
},
"bugs": {
"url": "https://github.com/postcss/postcss/issues"
},
"dependencies": {
"chalk": "^2.3.0",
"source-map": "^0.6.1",
"supports-color": "^4.4.0"
},
"description": "Tool for transforming styles with JS plugins",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-eslint": "^8.0.1",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-precompile-charcodes": "^1.1.0",
"babel-preset-env": "^1.6.1",
"concat-with-sourcemaps": "^1.0.4",
"del": "^3.0.0",
"docdash": "^0.4.0",
"eslint": "^4.10.0",
"eslint-config-postcss": "^2.0.2",
"fs-extra": "^4.0.2",
"gulp": "^3.9.1",
"gulp-babel": "^7.0.0",
"gulp-changed": "^3.1.1",
"gulp-eslint": "^4.0.0",
"gulp-jest": "^2.0.0",
"gulp-run": "^1.7.1",
"gulp-sourcemaps": "^2.6.1",
"jest": "^21.2.1",
"jsdoc": "^3.5.5",
"lint-staged": "^4.3.0",
"postcss-parser-tests": "^6.1.0",
"pre-commit": "^1.2.2",
"run-sequence": "^2.2.0",
"size-limit": "^0.12.1",
"strip-ansi": "^4.0.0",
"yaspeller-ci": "^0.7.0"
},
"engines": {
"node": ">=4.0.0"
},
"eslintConfig": {
"parser": "babel-eslint",
"extends": "eslint-config-postcss",
"rules": {
"consistent-return": "off",
"valid-jsdoc": "error",
"complexity": "off",
"no-new": "off"
},
"env": {
"browser": true,
"jest": true
}
},
"homepage": "http://postcss.org/",
"jest": {
"modulePathIgnorePatterns": [
"build"
]
},
"keywords": [
"css",
"postcss",
"rework",
"preprocessor",
"parser",
"source map",
"transform",
"manipulation",
"transpiler"
],
"license": "MIT",
"lint-staged": {
"test/*.js": "eslint",
"lib/*.es6": "eslint",
"*.md": "yaspeller-ci"
},
"main": "lib/postcss",
"name": "postcss",
"pre-commit": [
"lint-staged"
],
"repository": {
"type": "git",
"url": "git+https://github.com/postcss/postcss.git"
},
"scripts": {
"lint-staged": "lint-staged",
"test": "gulp"
},
"size-limit": [
{
"path": "lib/postcss.js",
"limit": "29 KB"
}
],
"types": "lib/postcss.d.ts",
"version": "6.0.14"
}