Giter Club home page Giter Club logo

preprocessor's Introduction

suitcss-preprocessor

Build Status Build status

SUIT CSS preprocessor.

Provides a CLI and Node.js interface for a preprocessor that combines various PostCSS plugins.

Compiles CSS packages with:

Each imported file is linted with postcss-bem-linter and stylelint. Minification is provided by cssnano.

Additional plugins can be added via the configuration options.

Installation

npm install suitcss-preprocessor

Usage

suitcss input.css output.css

API

Command Line

Options are documented below

Usage: suitcss [<input>] [<output>]

Options:

  -h, --help                output usage information
  -c, --config [path]       a custom PostCSS config file
  -i, --import-root [path]  the root directory for imported css files
  -s, --encapsulate         encapsulate component styles
  -w, --watch               watch the input file and any imports for changes
  -m, --minify              minify output with cssnano
  -e, --throw-error         throw an error when any warnings are found
  -L, --no-lint             disable stylelint and postcss-bem-linter
  -v, --verbose             log verbose output for debugging
  -V, --version             output the version number

Examples:

  # pass an input and output file:
  $ suitcss input.css output.css

  # configure the import root directory:
  $ suitcss --import-root src/css input.css output.css

  # watch the input file and imports for changes:
  $ suitcss --watch input.css output.css

  # configure postcss plugins with a config file:
  $ suitcss --config config.js input.css output.css

  # unix-style piping to stdin and stdout:
  $ cat input.css | suitcss | grep background-color

Node.js

Returns a PostCSS promise

preprocessor(css: String [, options: Object] [, filename: String]);
  • css: CSS input (required)
  • options: Options to the preprocessor (see below) (optional)
  • filename: Filename of the input CSS file (optional)

Example

var preprocessor = require('suitcss-preprocessor');
var fs = require('fs');

var filename = 'src/components/index.css';
var css = fs.readFileSync(filename, 'utf8');

preprocessor(css, {
  root: 'path/to/css',
  minify: true,
}, filename).then(function(result) {
  fs.writeFileSync('build/bundle.css', result.css);
});

Options

root

  • Type: String
  • Default: process.cwd()

Where to resolve imports from. Passed to postcss-import.

debug

  • Type: Function
  • Default: identity (it does nothing)

Before preprocessing debug is invoked on the postcss plugins array. This allows you to pass a postcss-debug instance.

var preprocessor = require('suitcss-preprocessor');
var createDebugger = require('postcss-debug').createDebugger;
var debug = createDebugger();

preprocessor(css, {
  debug: debug
}).then(function () {
  debug.inspect();
});

N.B. debug should always take one argument that is plugins and eventually return it:

function debug(plugins) {
  // do something with plugins here
  return plugins;
}

encapsulate

(experimental)

  • Type: Boolean
  • Default: false

Resets CSS properties to their initial values to effectively allow a component to opt out of CSS inheritance and be encapsulated from the rest of the application similar to the Shadow DOM. There are two types of CSS properties that affect components, inherited (e.g. font-size, color) and non-inherited (e.g. margin, background). This option works so that:

  • Root elements (e.g. .Component) have both inherited and non-inherited properties reset to default values.
  • Descendants (e.g. .Component-item) only have non-inherited properties reset as this allows properties set on the root element to be inherited by its descendants.

This means that components are isolated from styles outside the component root element but should an inheritable property such as font-size be applied on the component root element it will be inherited by the component descendants as normal. This prevents the need to redeclare properties on every descendant in a component.

The same rules also apply to nested components.

Rationale

One of the difficulties with CSS components is predictability. Unwanted styles can be inherited from parent components and this can make it difficult to reuse components in different contexts.

Methodologies such as SUIT and BEM exist to solve problems around the cascade and specificity but they cannot protect components from inheriting unwanted styles. What would really help is to allow inheritance to be 'opt-in' and let component authors decide what properties are inherited. This creates a more predictable baseline for styling components and promoting easier reuse.

Examples

What about all: initial?

The all: initial declaration will reset both inherited and non-inherited properties but this can be too forceful. For example display is reset to inline on block elements and as mentioned earlier, descendants of a component should only have non-inherited properties reset to allow declarations to be inherited from the root element.

For example, if an author specifies all: initial on an element it will block all inheritance and reset all properties, as if no rules appeared in the author, user, or user-agent levels of the cascade.

https://www.w3.org/TR/css3-cascade/#all-shorthand

Instead a subset of properties are reset to allow more granular control over what parts of a component use inheritance.

To achieve this the preprocessor uses postcss-autoreset with the SUIT preset and a custom set of CSS properties that are reset to their initial values. Only selectors conforming to the SUIT naming conventions are affected.

Caveats

Selectors must be present in the component CSS

If an element is present in the HTML but not styled in the component CSS (perhaps relying on utility classes) it will not be reset. In this instance an empty ruleset can be added to ensure it is correctly reset:

<div class="Component u-posRelative u-textCenter">
  <div class="Component-item"></div>
</div>
/**
 * Empty ruleset required.
 * Note the disabling of stylelint
 */

/* stylelint-disable-next-line block-no-empty */
.Component {}

.Component-item {
  color: red;
}
Global styles can still override descendants

Because component descendants only have non-inheritable properties reset it can lead to specific global rules still applying:

/* global.css */
span {
  color: red;
}

/* component.css */
.Component-text {
  font-style: bold;
}
<div class="Component">
  <span class="Component-text">
    <!-- this text is red -->
  <span>
</div>

The solution to this is to minimise or avoid entirely the use of global styles which is the recommended approach in a SUIT CSS application.

lint

  • Type: Boolean
  • Default: true

Ensure code conforms to the SUIT code style by using the stylelint-config-suitcss package.

Stylelint configuration options can also be overridden but this requires the stylelint-config-suitcss to be installed locally in your package.

{
  stylelint: {
    extends: 'stylelint-config-suitcss',
    rules: {
      indentation: [4, 'tab'],
    }
  }
}

minify

  • Type: Boolean
  • Default: false

If set to true then the output is minified by cssnano.

postcss

  • Type: Object
  • Default: undefined

Options that are passed directly to postcss, as per the documentation.

{
  postcss: {from: 'filename.css'}
}
use
  • Type: Array
  • Default: undefined

A list of plugins that are passed to PostCSS. This can be used to add new plugins and/or reorder the defaults

{
  use: ['postcss-at2x', 'postcss-property-lookup']
}

<plugin-name>

  • Type: Object
  • Default: undefined

Property matching the name of a PostCSS plugin that has options for that plugin

{
  autoprefixer: {
    browsers: ['> 1%', 'IE 7'],
    cascade: false
  },
  'postcss-calc': { preserve: true }
}

Plugin configuration

Creating a configuration file allows options to be passed to the individual PostCSS plugins. It can be passed to the suitcss CLI via the -c flag and can be either JavaScript or JSON

module.exports = {
  root: 'path/to/css',
  autoprefixer: { browsers: ['> 1%', 'IE 7'], cascade: false },
  'postcss-calc': { preserve: true }
}
{
  "root": "path/to/css",
  "autoprefixer": { "browsers": ["> 1%", "IE 7"], "cascade": false },
  "postcss-calc": { "preserve": true }
}

Options are merged recursively with the defaults. For example, adding new plugins to the use array will result in them being merged alongside the existing ones.

Adding additional plugins

By default the preprocessor uses all necessary plugins to build SUIT components. However additional plugins can be installed into a project and then added to the use array. They will be appended to the existing list of plugins.

Note: This will not work with the preprocessor installed globally. Instead rely on the convenience of npm run script

module.exports = {
  use: [
    'postcss-property-lookup'
  ]
};
{
  "name": "my-pkg",
  "version": "0.1.0",
  "dependencies": {
    "postcss-property-lookup": "^1.1.3",
    "suitcss-preprocessor": "^0.5.0"
  },
  "scripts": {
    "preprocess": "suitcss -c myconfig.js index.css build/built.css"
  }
}
npm run preprocess

Changing plugin order

If duplicate plugins are used they will be removed, but the new order will be respected. This is useful if you need to change the default order:

// Default order
var defaults = [
  'postcss-custom-properties',
  'postcss-calc',
  'postcss-color-function',
  'postcss-custom-media',
  'postcss-apply',
];

// config
module.exports = {
  use: [
    'postcss-at2x',
    'postcss-calc',
  ]
};

var result = [
  'postcss-custom-properties',
  'postcss-color-function',
  'postcss-custom-media',
  'postcss-apply',
  'postcss-at2x',
  'postcss-calc',
];

Note Some core plugins such as postcss-easy-import and autoprefixer cannot be re-ordered. This is to ensure components are preprocessed correctly.

Autoprefixer: vendor prefixes

By default the preprocessor uses the SUIT browserslist configuration:

> 1%, last 2 versions, safari > 6, ie > 9, ios > 6, android > 4.3, samsung > 3, chromeandroid > 50

The preprocessor doesn't attempt to find any browserslist config file.

Instead you can customise the browsers list via configuration file.

Acknowledgements

Based on Myth by Segment.io.

preprocessor's People

Contributors

casio avatar danalloway avatar giuseppeg avatar necolas avatar simonsmith avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

preprocessor's Issues

stylelint

Using version 3.0.0 of the suitcss preprocessor, stylelint is reporting warnings for the normalize.css in the node_modules directory:

node_modules/normalize.css/normalize.css
12:3    ⚠  Unexpected vendor-prefix "-ms-text-size-adjust" (property-no-vendor-prefix) [stylelint]
13:3    ⚠  Unexpected vendor-prefix "-webkit-text-size-adjust" (property-no-vendor-prefix) [stylelint]
96:3    ⚠  Unexpected vendor-prefix "-webkit-text-decoration-skip" (property-no-vendor-prefix) [stylelint]
212:1   ⚠  Unexpected composition (selector-root-no-composition) [stylelint]
306:3   ⚠  Unexpected vendor-prefix "-webkit-appearance" (property-no-vendor-prefix) [stylelint]
392:3   ⚠  Unexpected vendor-prefix "-webkit-appearance" (property-no-vendor-prefix) [stylelint]
402:3   ⚠  Unexpected vendor-prefix "-webkit-appearance" (property-no-vendor-prefix) [stylelint]
409:3   ⚠  Unexpected vendor-prefix "::-webkit-input-placeholder" (selector-no-vendor-prefix) [stylelint]
420:3   ⚠  Unexpected vendor-prefix "-webkit-appearance" (property-no-vendor-prefix) [stylelint]

I was able to suppress these warnings by including a .stylelintignore file in my project. I was looking through the stylelint-config-suitcss docs, and it seems like the intent is for the node_modules directory to be ignored by default?

How to use with alternative of postcss-import?

Hi, I try to use suitcss/preprocessor with postcss-easy-import and get unexpected behavior.

It seems that options.use is append-only.

merged.use = plugins.concat(options.use);

My config.js is following value:

const usePluginList = [
    "postcss-easy-import",
    "postcss-custom-properties",
    "postcss-calc",
    "postcss-custom-media",
    "autoprefixer",
    "postcss-reporter"
];
module.exports = {
    "root": "./src/css/",
    "use": usePluginList,
    "postcss-easy-import": {
        root: "./src/css/",
        glob: true
    }
};

Actual value of suitcss/preprocessor's options:

{ minify: undefined,
  lint: undefined,
  use: 
   [ 'postcss-import',
     'postcss-custom-properties',
     'postcss-calc',
     'postcss-custom-media',
     'autoprefixer',
     'postcss-reporter',
     'postcss-easy-import',
     'postcss-custom-properties',
     'postcss-calc',
     'postcss-custom-media',
     'autoprefixer',
     'postcss-reporter' ],
  'postcss-import': { onImport: [Function], root: './src/css/' },
  'postcss-reporter': { clearMessages: true },
  cssnano: 
   { calc: false,
     autoprefixer: false,
     mergeRules: false,
     safe: true },
  root: './src/css/',
  'postcss-easy-import': { root: './src/css/', glob: true } }

Expected value of suitcss/preprocessor's options:

{ minify: undefined,
  lint: undefined,
  use: 
   [ 'postcss-easy-import',
     'postcss-custom-properties',
     'postcss-calc',
     'postcss-custom-media',
     'autoprefixer',
     'postcss-reporter' ],
  'postcss-import': { onImport: [Function], root: './src/css/' },
  'postcss-reporter': { clearMessages: true },
  cssnano: 
   { calc: false,
     autoprefixer: false,
     mergeRules: false,
     safe: true },
  root: './src/css/',
  'postcss-easy-import': { root: './src/css/', glob: true } }

Deprecation of root rules

See the thread here - stylelint/stylelint#2226

It seems likely that if we want to keep these rules we should come up with a stylelint plugin. Maybe a good time to discuss the validity of the three root rules:

  • custom-property-no-outside-root
  • root-no-standard-properties
  • selector-root-no-composition

Remove beforeLint

I feel like this feature is probably unused and adds a lot of complexity to the preprocessor. I think it would also fix #27.

The only use case I had before was to unwrap nested rules for the bem-linter but it handles that out of the box now.

Thoughts?

Update stylelint version

Now it outputs this: Undefined rule "media-feature-parentheses-space-inside"
The new stylelint version fixes this.

Use one instance of postcss-reporter

Due to there being two instance of reporter (one in the transform callback, and the other in the main list of plugins) it causes issues with throwError.

An example is if throwError is set to true (for both reporters) then if custom-media throws an error but we choose just to care about postcss-bem-linter (via plugins config in reporter) then the error gets swallowed.

An example of needing this is in utils that have media queries that are missing. We want the custom media warnings to be ignored but the bem-lint and stylelint errors to be thrown. As these are handled by two different instance of reporter it doesn't throw an error at all. It works fine with warnings though, as I guess this is just a fancy stdout.

--import-root is being ignored

Give an entry file in <project-root>/src/index.css, running
$<project-root>: suitcss --import-root ./src index.css dist.css will throw:

not found · <project-root>/index.css

Seems, the option is just ignored?

Add debug option

It would be nice if we could pass an instance of postcss-debug via options.

import { createDebugger } from 'postcss-debug';
const debug = createDebugger();

suitcss(css, { debug }).then(()=>debug.inspect())

By default debug would be an identity function that does nothing:

var defaults = {
  debug: function (plugins) { return plugins; }
};

More on postcss-debug https://github.com/andywer/postcss-debug

Support double-slash comment style

I'm building a component-based application and am evaluating suitcss. I'm impressed, as it appears to be designed to suit (pun intended) my use case. I've used less, sass, stylus, etc. in the past, but am willing to switch to the best tool for the task.

However, the simple lack of // comment styles is quite annoying and makes it much harder to quickly comment and uncomment styles as I'm working on them. I understand that one objective of suitcss is to maintain future CSS standards, but it would be great if there was at least an option to use multiple commenting styles.

Lint main file

Currently if I pass this component:

/** @define Component */

@import "./util.css";

@custom-media --media-query (min-width: 200px);

:root {
  --Component-size: 16px;
}

.Component {
  font-size: var(--Component-size);
  width: calc(100% * 1 / 6);
}

.Component-item {
  display: flex;
}

@media (--media-query) {
  .Component-item {
    color: red;
  }
}

Only the util.css will be linted. Would be nice to lint the main file too.

Add postcss-initial to build chain.

postcss-autoreset uses initial which is not compatible with IE 11. postcss-autoreset actually recommends running css through postcss-initial as well to add support for IE 11. If suitcss wants to support IE 11 it should throw postcss-initial in the mix.

Lint by default

Thinking it makes more sense to have this on as a default.

Fail on empty import

suitcss fails on an empty import file, with the backtrace

error · TypeError: Cannot read property 'comment' of undefined
    ·   at conformance (usr/local/npm/node_modules/suitcss-preprocessor/node_modules/rework-suit/node_modules/rework-suit-conformance/index.js:29:36)

etc. Is this expected behavior?

Can be reproduced with suitcss foo.css, where foo.css is @import "./bar/css"; and bar.css is an empty file (zero-length).

CLI does not accept config file in json format

$ suitcss -c .suitconfig index.css raises like below when using a config file like

{
  "root": "src"
}
.suitconfig:2
  "root": "src"
        ^
SyntaxError: Unexpected token :
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (.../node_modules/suitcss-preprocessor/bin/suitcss:68:31)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)

Drop Node 0.12

It'd be good to use Argon (4.0) as the new minimum. Will allow some ES6 features to be used. Stylelint has already dropped it and PostCSS is due to in the next version.

Consider adding stylelint as a core feature

This stylelint-config-suitcss is useful, and the core packages should ideally be passing. Might make sense to incorporate it into the preprocessor, and perhaps move it behind a flag, as bem-linter is opt-in already (via comments). Users are free to toggle options via .stylelintrc once it's running.

Files need to be stylelinted on import, rather than as a package and it feels odd to do linting in the beforeLint step which would justify this addition.

Maybe stylelint-selector-bem-pattern could do the job in one go.

CLI options should override config file

Currently I think CLI options are overridden by the config file:

var opts = assign({}, {
      minify: program.minify,
      root: program.importRoot,
      lint: program.lint
    }, config);

AFAIK it's most common to be the other way round as it's often useful to be able to override a single config option on the CLI.

Should be a simple change and maybe a test to verify.

How use with Gulp?

Currently I still using this way:

gulp.task('suitcss', ['postcss'], () => {
  suitcss(fs.readFileSync(entryFile.css, 'utf8'), {
    minify: false,
  }).then(function(output) {
    fs.writeFileSync(outputFile.css, output.css);
  });
});

Is possible use with the gulp pipeline streaming, can you provide an example?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.