taro的CSS-in-JS方案

linaria

在taro中使用React开发,无法使用之前的styled-components的CSS方案。官方提供了一个linaria的一种CSS样式方案。这种方案与styled-components方案类似。

安装及使用

1.下载安装

1
yarn add linaria
  1. 配置 babel.config.js
1
2
3
4
5
6
7
8
9
module.exports = {
presets: [
['taro', {
framework: 'react',
ts: true
}],
'linaria/babel' // 添加到 babel-presets
]
}
  1. 配置 config/index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
const config = {
mini: {
webpackChain(chain, webpack) { // 添加到config-mini
chain.module
.rule('script')
.use('linariaLoader')
.loader('linaria/loader')
.options({
sourceMap: process.env.NODE_ENV !== 'production',
})
}
}
}
  1. 新建文件 linaria.config.js
1
2
3
module.exports = {
ignore: /node_modules[\/\\](?!@tarojs[\/\\]components)/,
}
  1. 使用方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React from "react"
import { View } from "@tarojs/components"
import { styled } from "linaria/react"

const Title = styled(View)`
color: #333;
background: red;
`

function Index(){
return (
<Title>
Hello World!
</Title>
)
}