简体   繁体   English

我如何在React组件中将postcss-bem与css-modules或postcss-js一起使用

[英]How could I use postcss-bem with css-modules or postcss-js in React component

I am learning how to use postcss-bem to generate css files in bem style, but I wonder if there're some package like the CSS-Modules or Postcss-JS, that I could use to doing something like below: 我正在学习如何使用becs风格的postcss-bem生成css文件,但是我想知道是否有一些像CSS-Modules或Postcss-JS这样的包,我可以用来做以下事情:

 const ReactComp extends React.Component{ render(){ let styles = './postcss-bem.css' return <div class={styles.blockname}>something</div> } } 

I found this feature on the documents of CSS-Modules and Postcss-JS but when I try to use webpack's postcss-loader with postcss-JS to parser the postcss-bem.css 我在CSS-Modules和Postcss-JS的文档中找到了此功能,但是当我尝试将webpack的postcss-loader与postcss-JS一起使用来解析postcss-bem.css时

loaders: ["style-loader","css-loader","postcss-loader?parser=postcss-js"] 加载程序:[“样式加载程序”,“ css加载程序”,“ postcss加载程序?parser = postcss-js”]

But I got the error like this 但是我得到这样的错误

Module build failed: SyntaxError: Unexpected token ILLEGAL 模块构建失败:SyntaxError:意外的令牌非法

Am I doing it wrong? 我做错了吗?

postcss-js is a CSS-in-JS solution, so it works with CSS written in JS. postcss-js是CSS-in-JS解决方案,因此可以与用JS编写的CSS一起使用。

According file extention, you use CSS, not JS in postcss-bem.css. 根据文件范围,在postcss-bem.css中使用CSS而不是JS。

Also there is no any sense to use postcss-bem plugin with CSS Modules. 同样,将postcss-bem插件与CSS模块一起使用也没有任何意义。 BEM allow you to isolate CSS by having prefix for every selector. BEM允许您通过为每个选择器添加前缀来隔离CSS。 But CSS Modules isolate CSS too. 但是CSS模块也可以隔离CSS。 So you this two PostCSS tools do same thing. 因此,您这两个PostCSS工具会做同样的事情。

Thanks Andrey, Here's my solution : using the css-loader to hash and load css token into js file. 谢谢Andrey,这是我的解决方案:使用css-loader将css令牌散列并加载到js文件中。

 //add these code into webpack.config.js module: { loaders: [ { test: /\\.css$/, loaders: [ 'style-loader', 'css-loader?' + 'modules&localIdentName=[name]_[local]_[hash:base64:3]', 'postcss-loader' ], } ] }, 

and in the JSX file, we can use import to load css token 在JSX文件中,我们可以使用import加载CSS令牌

 export default class Comp1 extends Component{ render () { const css = require( './style.css'); return <div className={css['Comp_name']}><Comp11 /></div>; } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM