[Go] Use Babel-plugin-react-css-modules to simplify the use of CSS modules

Source: Internet
Author: User
Tags postcss

In our product, we use CSS modules as a style solution, the approximate code is this:

ImportReactFrom' React ';ImportStylesFrom'./table.css ';ExportDefaultClassTableExtendsReact.Component{Render(){Return<DivClassName={Styles.Table}><DivClassName={Styles row}> <div classname={styles. Cell}>a0</div> Span class= "o" ><div classname={ styles. Cell}>b0</div> Span class= "o" ></div> </div>; }}             /span>                

But there are obviously some details of the trouble:

    1. Added a variable when you introduce a style styles
    2. Need to keep writing styles.xxx , repeating code

babel-plugin-react-css-modulesPlug-ins can mitigate these issues to some extent, making the code:

ImportReactFrom' React ';Import'./table.css ';ExportDefaultClassTableExtendsReact.Component{Render(){Return<div stylename= ' table ' > Span class= "o" ><div stylename= ' row ' > <div stylename= ' cell ' >a0</div> <div stylename= ' cell ' Span class= "o" >>b0</div> </div> </div>; }}             /span>                
Difficulties
    1. Our products use less rather than native CSS to write styles
    2. In order to generate a more beautiful class name, we used CSS modules with a custom getLocalIdent implementation
    3. There may be some difficulties in the integration with Webpack
Solution Installation Dependencies
npm i --save babel-plugin-react-css-modulesnpm i --save-dev postcss-less

It is important to note that babel-plugin-react-css-modules there is a runtime dependency, so the --save installation is better. and postcss-less then the syntax for parsing less

Adjusting the build configuration

Because there is a custom generated class name function, so the original .babelrc JSON format is not enough (cannot express the function), so we want to move the .babelrc configuration into babel-loader the options

After the move is complete, add the babel-plugin-react-css-modules plug-in to it, abstracting the function that generated the class name in the process:

ConstGeneratescopedname=(Name,FileName)={ConstHash=Hasha(FileName+Name,{Algorithm:' MD5 '});ConstBaseName=Path.BaseName(FileName,'. Less ');Return`${Dashcase(BaseName)}-${Name}-${Hash.Slice(0,5)}`;};Exports.Babel={Loader:' Babel-loader ',Options:{Cachedirectory:True,Presets:[// ... Preset Set],Plugins:[// ... Other plugins[' React-css-modules '{context: path join (__dirname "..." ), exclude:  ' node_modules '  Span class= "NX" >filetypes: {: {syntax:  ' postcss-less ' } }, generatescopedname: generatescopedname } ] ] }};      

The above file is webpack/loaders.js , the related configuration basically does not have to modify, uses as is the line. If the code is in a different location, context modify the configuration to correspond to the project root directory.

Then adjust the configuration of CSS modules related loader, reuse generateScopedName function:

Exports.Cssmodules={Loader:' Css-loader ',Options:{Sourcemap: developmentmodules: trueimportloaders: true camelcase:  ' dashes '  getlocalident ({resourcepath},  Localidentnamelocalname) { return generatescopedname (localname resourcepath); } }};           
Modify some source code

It is important to note that all .js the code referenced in the from IS .less not dependent on the Webpack resolve.modules configuration and can only write relative paths. That was originally written import ‘common/less/global.less‘ to be changed intoimport ‘./common/less/global.less‘

Then, according to the preference of the place has been used className to slowly change the styleName line.

[Go] Use Babel-plugin-react-css-modules to simplify the use of CSS modules

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.