styled-components Babel宏

2020-07-25 16:56 更新

Babel宏正在迅速獲得蒸汽作為一個(gè)功能齊全的選項(xiàng),以允許對(duì)零配置項(xiàng)目(如create-react-app)進(jìn)行高級(jí)代碼轉(zhuǎn)換

如果您的腳手架設(shè)置為bbel-plugin-macio,然后只需使用新的樣式組件/宏導(dǎo)入,而不是樣式組件:

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

宏包含我們的Babel 插件的所有功能,同時(shí)允許未彈出的工具來處理構(gòu)建過程的 Babel 部分。

實(shí)驗(yàn)配置

babel-plugin-macros使用cosmiconfig來閱讀它的配置,可以在導(dǎo)入文件目錄中以下任何文件中被定位到:

  • . 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

然后,您可以指定相同的選項(xiàng),我們的 babel插件樣式組件進(jìn)入:

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

有關(guān)詳細(xì)信息,請(qǐng)參閱實(shí)驗(yàn)配置的 babel-插件宏。

強(qiáng)制執(zhí)行宏導(dǎo)入

您可能希望確保對(duì)象在整個(gè)項(xiàng)目中始終從宏導(dǎo)入。這可以通過使用no-restricted-imports來自 Eslint 的規(guī)則:

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


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)