Что взять за основу react приложения

render Callback (>= v3.0.0)

node-sass supports standard node style asynchronous callbacks with the signature of . In error conditions, the argument is populated with the error object. In success conditions, the object is populated with an object describing the result of the render call.


  • (String) — The error message.
  • (Number) — The line number of error.
  • (Number) — The column number of error.
  • (Number) — The status code.
  • (String) — The filename of error. In case option was not set (in favour of ), this will reflect the value .
  • (Buffer) — The compiled CSS. Write this to a file, or serve it out as needed.
  • (Buffer) — The source map
  • (Object) — An object containing information about the compile. It contains the following keys:
    • (String) — The path to the scss file, or if the source was not a file
    • (Number) — Date.now() before the compilation
    • (Number) — Date.now() after the compilation
    • (Number) — end — start
    • (Array) — Absolute paths to all related scss files in no particular order.
var sass =require('node-sass');sass.render({  file'/path/to/myFile.scss',  data'body{background:blue; a{color:black;}}',importerfunction(url,prev,done){someAsyncFunction(url, prev,function(result){done({        fileresult.path,        contentsresult.data});});var result =someSyncFunction(url, prev);return{fileresult.path, contentsresult.data};},  includePaths'lib/','mod/',  outputStyle'compressed'},function(error,result){if(error){console.log(error.status);console.log(error.column);console.log(error.message);console.log(error.line);}else{console.log(result.css.toString());console.log(result.stats);console.log(result.map.toString());console.log(JSON.stringify(result.map));}});var result =sass.renderSync({  file'/path/to/file.scss',  data'body{background:blue; a{color:black;}}',  outputStyle'compressed',  outFile'/to/my/output.css',  sourceMaptrue,importerfunction(url,prev,done){someAsyncFunction(url, prev,function(result){done({        fileresult.path,        contentsresult.data});});var result =someSyncFunction(url, prev);return{fileresult.path, contentsresult.data};}}));console.log(result.css);console.log(result.map);console.log(result.stats);

In the case that both file and data options are set, node-sass will give precedence to data and use file to calculate paths in sourcemaps.

Both and version info is now exposed via the method:

var sass =require('node-sass');console.log(sass.info);

Since node-sass >=v3.0.0 LibSass version is determined at run time.

Command Line Interface

The interface for command-line usage is fairly simplistic at this stage, as seen in the following usage section.

Output will be sent to stdout if the flag is omitted.

Or:

Example:

Options:

    -w, --watch                Watch a directory or file    -r, --recursive            Recursively watch directories or files    -o, --output               Output directory    -x, --omit-source-map-url  Omit source map URL comment from output    -i, --indented-syntax      Treat data from stdin as sass code (versus scss)    -q, --quiet                Suppress log output except on error    -v, --version              Prints version info    --output-style             CSS output style (nested | expanded | compact | compressed)    --indent-type              Indent typeforoutput CSS (space | tab)    --indent-width             Indent width; number of spaces or tabs (maximum value: 10)    --linefeed                 Linefeed style (cr | crlf | lf | lfcr)    --source-comments          Include debug info in output    --source-map               Emit source map    --source-map-contents      Embed include contents in map    --source-map-embed         Embed sourceMappingUrl as data URI    --source-map-root          Base path, will be emitted insource-map as is    --include-path             Path to look forimported files    --follow                   Follow symlinked directories    --precision                The amount of precision allowed in decimal numbers    --error-bell               Output a bell character on errors    --importer                 Path to .js file containing custom importer    --functions                Path to .js file containing custom functions    --help                     Print usage info

The can be either a single or , or a directory. If the input is a directory the flag must also be supplied.

The option accepts a boolean value, in which case it replaces destination extension with . It also accepts path to file and even path to the desired directory. When compiling a directory can either be a boolean value or a directory.

Options

  • Type:
  • Default:

Special: or must be specified

  • Type:
  • Default:

Special: or must be specified

This is an experimental LibSass feature. Use with caution.

  • Type: signature
  • Default:

Function Parameters and Information:

  • — the previously resolved path
  • — a callback function to invoke on async completion, takes an object literal containing
    • — the imported contents (for example, read from memory or the file system)

When returning or calling with , the new file path will be assumed for the . It’s recommended to be mindful of the value of in instances where relative path resolution may be required.

When returning or calling with , the string value will be used as if the file was read in through an external source.

Starting from v3.0.0:

  • refers to a contextual scope for the immediate run of or

  • importers can return error and LibSass will emit that error in response. For instance:

    done(newError('doesn\'t exist!'));returnnewError('nothing to do here');

This is an experimental LibSass feature. Use with caution.

is an that holds a collection of custom functions that may be invoked by the sass files being compiled. They may take zero or more input parameters and must return a value either synchronously () or asynchronously (). Those parameters will be instances of one of the constructors contained in the hash. The return value must be of one of these types as well. See the list of available types below:

  • / : gets / sets the numerical portion of the number
  • / : gets / sets the unit portion of the number

getValue() / setValue(value) : gets / sets the enclosed string

  • / : red component (integer from to )
  • / : green component (integer from to )
  • / : blue component (integer from to )
  • / : alpha component (number from to )

Example:

var Color =require('node-sass').types.Color,  c1 =newColor(255,,),  c2 =newColor(0xff0088cc);
  • : gets the enclosed boolean
  • : Singleton instance of that holds «true»
  • : Singleton instance of that holds «false»
  • / : must itself be an instance of one of the constructors in .
  • / : whether to use commas as a separator

types.Null.NULL : Singleton instance of types.Null.

sass.renderSync({  data'#{headings(2,5)} { color: #08c; }',  functions{'headings($from: 0, $to: 6)'function(from,to){var i, f =from.getValue(), t =to.getValue(),          list =newsass.types.List(t - f +1);for(i = f; i <= t; i++){list.setValue(i - f,newsass.types.String('h'+ i));}return list;}}});
  • Type:
  • Default:
  • Type:
  • Default:

Note: node-sass/libsass will compile a mixed library of scss and indented syntax (.sass) files with the Default setting (false) as long as .sass and .scss extensions are used in filenames.

  • Type:
  • Default:

Used to determine whether to use space or tab character for indentation.

  • Type:
  • Default:
  • Maximum:

Used to determine the number of spaces or tabs to be used for indentation.

  • Type:
  • Default:

Used to determine whether to use , , or sequence for line break.

  • Type:
  • Default:

Special: When using this, you should also specify to avoid unexpected behavior.

values disable the inclusion of source map information in the output file.

  • Type:
  • Default:

Special: Required when is a truthy value

Specify the intended location of the output file. Strongly recommended when outputting source maps so that they can properly refer back to their intended files.

Attention enabling this option will not write the file on disk for you, it’s for internal reference purpose only (to generate the map for example).

Example on how to write it on the disk

sass.render({...    outFile yourPathTotheFile,},function(error,result){if(!error){fs.writeFile(yourPathTotheFile,result.css,function(err){if(!err){}});}});});
  • Type:
  • Default:
  • Values: , , ,

Determines the output format of the final CSS style.

  • Type:
  • Default:

Used to determine how many digits after the decimal will be allowed. For instance, if you had a decimal number of and a precision of , the result will be in the final CSS.

  • Type:
  • Default:

Enables the line number and file where a selector is defined to be emitted into the compiled CSS as a comment. Useful for debugging, especially when using imports and mixins.

  • Type:
  • Default:

Special: Setting the option requires also setting the option

Enables the outputting of a source map during and . When , the value of is used as the target output location for the source map. When , the value of will be used as the writing location for the file.

  • Type:
  • Default:

includes the in the source map information

  • Type:
  • Default:

embeds the source map as a data URI

  • Type:
  • Default:

the value will be emitted as in the source map information

Class Composition

CSS Modules promote composition pattern, i.e. every CSS Module that is used in a component should define all properties required to describe an element, e.g.

.box{width100px;height100px;}.empty{composesbox;background#4CAF50;}.full{composesbox;background#F44336;}

Composition promotes better separation of markup and style using semantics that would be hard to achieve without CSS Modules.

Because CSS Module names are local, it is perfectly fine to use generic style names such as «empty» or «full», without «box-» prefix.

Consider the same example in CSS and HTML:

.box{width100px;height100px;}.box-empty{background#4CAF50;}.box-full{background#F44336;}
<divclass='box box-empty'><div>

This pattern emerged with the advent of OOCSS. The biggest disadvantage of this implementation is that you will need to change HTML almost every time you want to change the style.

Using :

%box {width100px;height100px;}.box-empty{    @extend %box;background#4CAF50;}.box-full{    @extend %box;background#F44336;}

This translates to:

.box-empty,.box-full{width100px;height100px;}.box-empty{background#4CAF50;}.box-full{background#F44336;}

Using mixins:

@mixin box {width100px;height100px;}.box-empty{    @includebox;background#4CAF50;}.box-full{    @includebox;background#F44336;}

This translates to:

.box-empty{width100px;height100px;background#4CAF50;}.box-full{width100px;height100px;background#F44336;}

Command Line Interface

The interface for command-line usage is fairly simplistic at this stage, as seen in the following usage section.

Output will be sent to stdout if the flag is omitted.

Or:

Example:

Options:

    -w, --watch                Watch a directory or file    -r, --recursive            Recursively watch directories or files    -o, --output               Output directory    -x, --omit-source-map-url  Omit source map URL comment from output    -i, --indented-syntax      Treat data from stdin as sass code (versus scss)    -q, --quiet                Suppress log output except on error    -v, --version              Prints version info    --output-style             CSS output style (nested | expanded | compact | compressed)    --indent-type              Indent typeforoutput CSS (space | tab)    --indent-width             Indent width; number of spaces or tabs (maximum value: 10)    --linefeed                 Linefeed style (cr | crlf | lf | lfcr)    --source-comments          Include debug info in output    --source-map               Emit source map    --source-map-contents      Embed include contents in map    --source-map-embed         Embed sourceMappingUrl as data URI    --source-map-root          Base path, will be emitted insource-map as is    --include-path             Path to look forimported files    --follow                   Follow symlinked directories    --precision                The amount of precision allowed in decimal numbers    --error-bell               Output a bell character on errors    --importer                 Path to .js file containing custom importer    --functions                Path to .js file containing custom functions    --help                     Print usage info

The can be either a single or , or a directory. If the input is a directory the flag must also be supplied.

The option accepts a boolean value, in which case it replaces destination extension with . It also accepts path to file and even path to the desired directory. When compiling a directory can either be a boolean value or a directory.

Class Composition

CSS Modules promote composition pattern, i.e. every CSS Module that is used in a component should define all properties required to describe an element, e.g.

.box{width100px;height100px;}.empty{composesbox;background#4CAF50;}.full{composesbox;background#F44336;}

Composition promotes better separation of markup and style using semantics that would be hard to achieve without CSS Modules.

Because CSS Module names are local, it is perfectly fine to use generic style names such as «empty» or «full», without «box-» prefix.

Consider the same example in CSS and HTML:

.box{width100px;height100px;}.box-empty{background#4CAF50;}.box-full{background#F44336;}
<divclass='box box-empty'><div>

This pattern emerged with the advent of OOCSS. The biggest disadvantage of this implementation is that you will need to change HTML almost every time you want to change the style.

Using :

%box {width100px;height100px;}.box-empty{    @extend %box;background#4CAF50;}.box-full{    @extend %box;background#F44336;}

This translates to:

.box-empty,.box-full{width100px;height100px;}.box-empty{background#4CAF50;}.box-full{background#F44336;}

Using mixins:

@mixin box {width100px;height100px;}.box-empty{    @includebox;background#4CAF50;}.box-full{    @includebox;background#F44336;}

This translates to:

.box-empty{width100px;height100px;background#4CAF50;}.box-full{width100px;height100px;background#F44336;}

render Callback (>= v3.0.0)

node-sass supports standard node style asynchronous callbacks with the signature of . In error conditions, the argument is populated with the error object. In success conditions, the object is populated with an object describing the result of the render call.

  • (String) — The error message.
  • (Number) — The line number of error.
  • (Number) — The column number of error.
  • (Number) — The status code.
  • (String) — The filename of error. In case option was not set (in favour of ), this will reflect the value .
  • (Buffer) — The compiled CSS. Write this to a file, or serve it out as needed.
  • (Buffer) — The source map
  • (Object) — An object containing information about the compile. It contains the following keys:
    • (String) — The path to the scss file, or if the source was not a file
    • (Number) — Date.now() before the compilation
    • (Number) — Date.now() after the compilation
    • (Number) — end — start
    • (Array) — Absolute paths to all related scss files in no particular order.
var sass =require('node-sass');sass.render({  file'/path/to/myFile.scss',  data'body{background:blue; a{color:black;}}',importerfunction(url,prev,done){someAsyncFunction(url, prev,function(result){done({        fileresult.path,        contentsresult.data});});var result =someSyncFunction(url, prev);return{fileresult.path, contentsresult.data};},  includePaths'lib/','mod/',  outputStyle'compressed'},function(error,result){if(error){console.log(error.status);console.log(error.column);console.log(error.message);console.log(error.line);}else{console.log(result.css.toString());console.log(result.stats);console.log(result.map.toString());console.log(JSON.stringify(result.map));}});var result =sass.renderSync({  file'/path/to/file.scss',  data'body{background:blue; a{color:black;}}',  outputStyle'compressed',  outFile'/to/my/output.css',  sourceMaptrue,importerfunction(url,prev,done){someAsyncFunction(url, prev,function(result){done({        fileresult.path,        contentsresult.data});});var result =someSyncFunction(url, prev);return{fileresult.path, contentsresult.data};}}));console.log(result.css);console.log(result.map);console.log(result.stats);

In the case that both file and data options are set, node-sass will give precedence to data and use file to calculate paths in sourcemaps.

Both and version info is now exposed via the method:

var sass =require('node-sass');console.log(sass.info);

Since node-sass >=v3.0.0 LibSass version is determined at run time.

API

Makes available a context to use in styled components. The shape of the theme object consists of an object whose keys are identifiers for styled components provided with the function with each theme as the corresponding value. Useful for ui-kits.

Returns a to wrap a component and make it themeable.


The returned component accepts a , , and props apart from the props of the original component. They former two are used to provide a to the component and to configure the style composition, which can be configured via options too. is used to pass a ref callback to the decorated component and is a function that can be used to map properties to the decorated component. The function arguments are:

  • (String) used to provide a unique identifier to the component that will be used to get a theme from context.
  • (Object) is classname object resolved from CSS modules. It will be used as the default theme to calculate a new theme that will be passed to the component.
  • (Object) If specified it allows to customize the behavior:
    • [] (String) allows to customize the way themes are merged or to disable merging completely. The accepted values are to deeply merge themes, to softly merge themes and to disable theme merging.
    • [] (Function) allows to customize how properties are passed down to the decorated component. By default, themr extracts all own properties passing down just as and the generated theme as . If you are decorating a component that needs to map the reference or any other custom property, this function is called with all properties given to the component plus the generated in the second parameter. It should return the properties you want to pass.

Options

  • Type:
  • Default:

Special: or must be specified

  • Type:
  • Default:

Special: or must be specified

This is an experimental LibSass feature. Use with caution.

  • Type: signature
  • Default:

Function Parameters and Information:

  • — the previously resolved path
  • — a callback function to invoke on async completion, takes an object literal containing
    • — the imported contents (for example, read from memory or the file system)

When returning or calling with , the new file path will be assumed for the . It’s recommended to be mindful of the value of in instances where relative path resolution may be required.

When returning or calling with , the string value will be used as if the file was read in through an external source.

Starting from v3.0.0:

  • refers to a contextual scope for the immediate run of or

  • importers can return error and LibSass will emit that error in response. For instance:

    done(newError('doesn\'t exist!'));returnnewError('nothing to do here');

This is an experimental LibSass feature. Use with caution.

is an that holds a collection of custom functions that may be invoked by the sass files being compiled. They may take zero or more input parameters and must return a value either synchronously () or asynchronously (). Those parameters will be instances of one of the constructors contained in the hash. The return value must be of one of these types as well. See the list of available types below:

  • / : gets / sets the numerical portion of the number
  • / : gets / sets the unit portion of the number

getValue() / setValue(value) : gets / sets the enclosed string

  • / : red component (integer from to )
  • / : green component (integer from to )
  • / : blue component (integer from to )
  • / : alpha component (number from to )

Example:

var Color =require('node-sass').types.Color,  c1 =newColor(255,,),  c2 =newColor(0xff0088cc);
  • : gets the enclosed boolean
  • : Singleton instance of that holds «true»
  • : Singleton instance of that holds «false»
  • / : must itself be an instance of one of the constructors in .
  • / : whether to use commas as a separator

types.Null.NULL : Singleton instance of types.Null.

sass.renderSync({  data'#{headings(2,5)} { color: #08c; }',  functions{'headings($from: 0, $to: 6)'function(from,to){var i, f =from.getValue(), t =to.getValue(),          list =newsass.types.List(t - f +1);for(i = f; i <= t; i++){list.setValue(i - f,newsass.types.String('h'+ i));}return list;}}});
  • Type:
  • Default:
  • Type:
  • Default:

Note: node-sass/libsass will compile a mixed library of scss and indented syntax (.sass) files with the Default setting (false) as long as .sass and .scss extensions are used in filenames.

  • Type:
  • Default:

Used to determine whether to use space or tab character for indentation.

  • Type:
  • Default:
  • Maximum:

Used to determine the number of spaces or tabs to be used for indentation.

  • Type:
  • Default:

Used to determine whether to use , , or sequence for line break.

  • Type:
  • Default:

Special: When using this, you should also specify to avoid unexpected behavior.

values disable the inclusion of source map information in the output file.

  • Type:
  • Default:

Special: Required when is a truthy value

Specify the intended location of the output file. Strongly recommended when outputting source maps so that they can properly refer back to their intended files.

Attention enabling this option will not write the file on disk for you, it’s for internal reference purpose only (to generate the map for example).

Example on how to write it on the disk

sass.render({...    outFile yourPathTotheFile,},function(error,result){if(!error){fs.writeFile(yourPathTotheFile,result.css,function(err){if(!err){}});}});});
  • Type:
  • Default:
  • Values: , , ,

Determines the output format of the final CSS style.

  • Type:
  • Default:

Used to determine how many digits after the decimal will be allowed. For instance, if you had a decimal number of and a precision of , the result will be in the final CSS.

  • Type:
  • Default:

Enables the line number and file where a selector is defined to be emitted into the compiled CSS as a comment. Useful for debugging, especially when using imports and mixins.

  • Type:
  • Default:

Special: Setting the option requires also setting the option

Enables the outputting of a source map during and . When , the value of is used as the target output location for the source map. When , the value of will be used as the writing location for the file.

  • Type:
  • Default:

includes the in the source map information

  • Type:
  • Default:

embeds the source map as a data URI

  • Type:
  • Default:

the value will be emitted as in the source map information

Performance

The important metric here is the «Difference from the base benchmark». «base» is defined as using React with hardcoded values. The lesser the difference, the bigger the performance impact.

Name Operations per second (relative margin of error) Sample size Difference from the base benchmark
Using (base) 9551 (±1.47%) 587 -0%
5914 (±2.01%) 363 -61%
(runtime, anonymous) 9145 (±1.94%) 540 -4%
(runtime, named) 8786 (±1.59%) 527 -8%

Run the benchmark:

git clone git@github.com:gajus/babel-plugin-react-css-modules.gitcd ./babel-plugin-react-css-modulesnpm installnpm run buildcd ./benchmarknpm installNODE_ENV=production ./test

Example transpilations

When is a literal string value, resolves the value of at the compile time.


Input:

import'./bar.css';<div styleName="a"><div>;

Output:

import'./bar.css';<div className="bar___a"><div>;

Input:

importfoofrom'./foo1.css';importbarfrom'./bar1.css';<div styleName="foo.a"><div>;<div styleName="bar.a"><div>;

Output:

importfoofrom'./foo1.css';importbarfrom'./bar1.css';<div className="foo___a"><div>;<div className="bar___a"><div>;

Input:

import'./bar.css';<div styleName={Math.random()>.5?'a''b'}><div>;

Output:

import_getClassNamefrom'babel-plugin-react-css-modules/dist/browser/getClassName';importfoofrom'./bar.css';const_styleModuleImportMap={  foo{    a'bar__a',    b'bar__b'}};<div styleName={_getClassName(Math.random()>.5?'a''b', _styleModuleImportMap)}><div>;

CSS Modules

In the context of React, CSS Modules look like this:

importReactfrom'react';importstylesfrom'./table.css';exportdefaultclassTableextendsReact.Component{render(){return<div className={styles.table}><div className={styles.row}><div className={styles.cell}>A0<div><div className={styles.cell}>B0<div><div><div>;}}

Rendering the component will produce a markup similar to:

<div class="table__table___32osj"><div class="table__row___2w27N"><div class="table__cell___1oVw5">A0<div><div class="table__cell___1oVw5">B0<div><div><div>

and a corresponding CSS file that matches those CSS classes.

Awesome!

Command Line Interface

The interface for command-line usage is fairly simplistic at this stage, as seen in the following usage section.

Output will be sent to stdout if the flag is omitted.

Or:

Example:

Options:

    -w, --watch                Watch a directory or file    -r, --recursive            Recursively watch directories or files    -o, --output               Output directory    -x, --omit-source-map-url  Omit source map URL comment from output    -i, --indented-syntax      Treat data from stdin as sass code (versus scss)    -q, --quiet                Suppress log output except on error    -v, --version              Prints version info    --output-style             CSS output style (nested | expanded | compact | compressed)    --indent-type              Indent typeforoutput CSS (space | tab)    --indent-width             Indent width; number of spaces or tabs (maximum value: 10)    --linefeed                 Linefeed style (cr | crlf | lf | lfcr)    --source-comments          Include debug info in output    --source-map               Emit source map    --source-map-contents      Embed include contents in map    --source-map-embed         Embed sourceMappingUrl as data URI    --source-map-root          Base path, will be emitted insource-map as is    --include-path             Path to look forimported files    --follow                   Follow symlinked directories    --precision                The amount of precision allowed in decimal numbers    --error-bell               Output a bell character on errors    --importer                 Path to .js file containing custom importer    --functions                Path to .js file containing custom functions    --help                     Print usage info

The can be either a single or , or a directory. If the input is a directory the flag must also be supplied.

The option accepts a boolean value, in which case it replaces destination extension with . It also accepts path to file and even path to the desired directory. When compiling a directory can either be a boolean value or a directory.

How does it work?

Say you have a component you want to make themeable. You should pass a unique name identifier that will be used to retrieve its theme from context in case it is present.

import React,{ Component }from'react';import{ themr }from'react-css-themr';@themr('MyThemedButton')classButtonextendsComponent{render(){const{theme,icon,children}=this.props;return(<buttonclassName={theme.button}>{ icon ?<iclassName={theme.icon}>{icon}</i>null}<spanclassName={theme.content}>{children}</span></button>)}}exportdefaultButton;

The component is defining an API for theming that consists of three classnames: button, icon and content. Now, a component can use a button with a success theme like:

import Button from'./Button';import successTheme from'./SuccessButton.css';exportdefault(props)=>(<div{...props}><p>Do you like it?</p><Buttontheme={successTheme}>Yeah!</Button></div>);

If you use a component with a base theme, you may want to import the component with the theme already injected. Then you can compose its style via props with another theme object. In this case the base css will always be bundled:

import React,{ Component }from'react';import{ themr }from'react-css-themr';import successTheme from'./SuccessButton.css';@themr('MySuccessButton', successTheme)classButtonextendsComponent{render(){const{theme,icon,children}=this.props;return(<buttonclassName={theme.button}>{ icon ?<iclassName={theme.icon}>{icon}</i>null}<spanclassName={theme.content}>{children}</span></button>)}}exportdefaultButton;

Imagine you want to make the success button uppercase for a specific case. You can include the classname mixed with other classnames:

import React from'react';import SuccessButton from'SuccessButon';import style from'./Section.css';exportdefault()=>(<sectionclassName={style.section}><SuccessButtontheme={style.button}>Yai!</SuccessButton></section>);

And being something like:

.section{border1pxsolidred;}.button{text-transformuppercase;}

The final classnames object for the component would include class values from and so it would be uppercase!

import React from'react';import{ render }from'react-dom';import{ ThemeProvider }from'react-css-themr';import App from'./app'constcontextTheme={  RTButtonrequire('react-toolbox/lib/button/style.scss'),  RTDialogrequire('react-toolbox/lib/dialog/style.scss')};constcontent=(<ThemeProvidertheme={contextTheme}><App/></ThemeProvider>);render(content,document.getElementById('app'));

The main idea is to inject classnames objects for each component via context. This way you can have the whole theme in a single place and forget about including styles in every require. Any component or from will use the provided styles in the context.

render Callback (>= v3.0.0)

node-sass supports standard node style asynchronous callbacks with the signature of . In error conditions, the argument is populated with the error object. In success conditions, the object is populated with an object describing the result of the render call.

  • (String) — The error message.
  • (Number) — The line number of error.
  • (Number) — The column number of error.
  • (Number) — The status code.
  • (String) — The filename of error. In case option was not set (in favour of ), this will reflect the value .
  • (Buffer) — The compiled CSS. Write this to a file, or serve it out as needed.
  • (Buffer) — The source map
  • (Object) — An object containing information about the compile. It contains the following keys:
    • (String) — The path to the scss file, or if the source was not a file
    • (Number) — Date.now() before the compilation
    • (Number) — Date.now() after the compilation
    • (Number) — end — start
    • (Array) — Absolute paths to all related scss files in no particular order.
var sass =require('node-sass');sass.render({  file'/path/to/myFile.scss',  data'body{background:blue; a{color:black;}}',importerfunction(url,prev,done){someAsyncFunction(url, prev,function(result){done({        fileresult.path,        contentsresult.data});});var result =someSyncFunction(url, prev);return{fileresult.path, contentsresult.data};},  includePaths'lib/','mod/',  outputStyle'compressed'},function(error,result){if(error){console.log(error.status);console.log(error.column);console.log(error.message);console.log(error.line);}else{console.log(result.css.toString());console.log(result.stats);console.log(result.map.toString());console.log(JSON.stringify(result.map));}});var result =sass.renderSync({  file'/path/to/file.scss',  data'body{background:blue; a{color:black;}}',  outputStyle'compressed',  outFile'/to/my/output.css',  sourceMaptrue,importerfunction(url,prev,done){someAsyncFunction(url, prev,function(result){done({        fileresult.path,        contentsresult.data});});var result =someSyncFunction(url, prev);return{fileresult.path, contentsresult.data};}}));console.log(result.css);console.log(result.map);console.log(result.stats);

In the case that both file and data options are set, node-sass will give precedence to data and use file to calculate paths in sourcemaps.

Both and version info is now exposed via the method:

var sass =require('node-sass');console.log(sass.info);

Since node-sass >=v3.0.0 LibSass version is determined at run time.

Binary configuration parameters

node-sass supports different configuration parameters to change settings related to the sass binary such as binary name, binary path or alternative download path. Following parameters are supported by node-sass:

Variable name .npmrc parameter Process argument Value
SASS_BINARY_NAME sass_binary_name —sass-binary-name path
SASS_BINARY_SITE sass_binary_site —sass-binary-site URL
SASS_BINARY_PATH sass_binary_path —sass-binary-path path
SASS_BINARY_DIR sass_binary_dir —sass-binary-dir path

These parameters can be used as environment variable:

E.g. export SASS_BINARY_SITE=http://example.com/

E.g. sass_binary_site=http://example.com/

As a process argument:

E.g. npm install node-sass —sass-binary-site=http://example.com/

What’s the Problem?

  • You have to use CSS class names.
  • You have to use object whenever constructing a .
  • Mixing CSS Modules and global CSS classes is cumbersome.
  • Reference to an undefined CSS Module resolves to without a warning.

React CSS Modules component automates loading of CSS Modules using property, e.g.

importReactfrom'react';importCSSModulesfrom'react-css-modules';importstylesfrom'./table.css';classTableextendsReact.Component{render(){return<div styleName='table'><div styleName='row'><div styleName='cell'>A0<div><div styleName='cell'>B0<div><div><div>;}}exportdefaultCSSModules(Table, styles);

Using :

  • You are not forced to use the naming convention.
  • You do not need to refer to the object every time you use a CSS Module.
  • There is clear distinction between global CSS and CSS Modules, e.g.
<div className='global-css' styleName='local-module'><div>

Combining CSS modules

There are three possible sources for your component. Sorted by priority: context, configuration and props. Any of them can be missing. In case multiple themes are present, you may want to compose the final classnames object in three different ways:

  • Override: the theme object with the highest priority is the one used.
  • Softly merging: theme objects are merged but if a key is present in more than one object, the final value corresponds to the theme with highest priority.
  • Deeply merging: theme objects are merged and if a key is present in more than one object, the values for each objects are concatenated.

You can choose whatever you want. We consider the last one as the most flexible so it’s selected by default.


С этим читают