styled-components Babel宏

2020-07-25 16:56 更新

Babel宏正在迅速获得蒸汽作为一个功能齐全的选项,以允许对零配置项目(如create-react-app)进行高级代码转换

如果您的脚手架设置为bbel-plugin-macio,然后只需使用新的样式组件/宏导入,而不是样式组件:

import styled, { createGlobalStyle } from 'styled-components/macro'
const Thing = styled.div`
color: red;
`
const GlobalStyle = createGlobalStyle`
body {
color: 'white';
}
`

宏包含我们的Babel 插件的所有功能,同时允许未弹出的工具来处理构建过程的 Babel 部分。

实验配置

babel-plugin-macros使用cosmiconfig来阅读它的配置,可以在导入文件目录中以下任何文件中被定位到:

  • . babel - plugin - 宏
  • . babel - plugin - macrosrc. json
  • . babel - plugin - macrosrc. yaml
  • . babel - plugin - macrosrc. yml
  • . babel - plugin - macrosrc. js
  • babel - plugin - 宏. config. js
  • babelMacros in package.json

然后,您可以指定相同的选项,我们的 babel插件样式组件进入:

// babel-plugin-macros.config.js
module.exports = {
// ...
// Other macros config
styledComponents: {
pure: true,
},
}

有关详细信息,请参阅实验配置的 babel-插件宏

强制执行宏导入

您可能希望确保对象在整个项目中始终从宏导入。这可以通过使用no-restricted-imports来自 Eslint 的规则:

"no-restricted-imports": [
"error",
{
"paths": [{
"name": "styled-components",
"message": "Please import from styled-components/macro."
}],
"patterns": [
"!styled-components/macro"
]
}
]


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号