Use CSS-in-JS
linaria
There is a common CSS-in-JS solution in the React community: styled-components。Unfortunately, however, styled-components
uses the <style>
tag to dynamically control styles, and there is no similar solution in mini program. But we can achieve the same functionality with linaria, linaria
mainly provides the following features.
- API that approximates
styled-components
- TypeScript support
- Zero runtime
Using linaria
is also very simple, first installing the dependencies via NPM:
$ pnpm i @linaria/core @linaria/react @linaria/babel-preset @linaria/webpack-loader
Next, configure babel.config.js
in the project root directory:
babel.config.js
module.exports = {
presets: [
['taro', {
framework: 'react',
ts: true
}],
'@linaria' // 添加到 babel-preset
]
}
After that, configure config/index.js
config/index.js
const config = {
mini: {
webpackChain(chain, webpack) {
// linaria/loader options refer to https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md#webpack
chain.module
.rule('script')
.use('linariaLoader')
.loader('@linaria/webpack-loader')
.options({
sourceMap: process.env.NODE_ENV !== 'production',
})
}
},
h5: {
webpackChain(chain, webpack) {
chain.module
.rule('script')
.use('linariaLoader')
.loader('@linaria/webpack-loader')
.options({
sourceMap: process.env.NODE_ENV !== 'production',
})
}
}
}
Finally, create a new linaria.config.js
in the root of the project
linaria.config.js
// linaria configuration details: https://github.com/callstack/linaria/blob/master/docs/CONFIGURATION.md#options
module.exports = {
rules: [
{
action: require("@linaria/shaker").default,
},
{
test: /node_modules[\/\\](?!@tarojs)/,
action: "ignore"
}
]
}
In the business code we can use it like this.
- JavaScript
- TypeScript
import { styled } from '@linaria/react'
import { View } from '@tarojs/components'
import React from 'react'
const Title = styled(View)`
color: ${props => props.color}
`;
const Index = () => {
return <Title color='red'>
Hello World!
</Title>
}
export default Index
import { styled } from '@linaria/react'
import { View, ViewProps } from '@tarojs/components'
import React from 'react'
import './index.scss'
declare type Component<TProps> = ((props: TProps) => any) | {
new (props: TProps): any
}
type VPS = ViewProps & { style?: React.CSSProperties }
type TP = VPS & { color: string }
const Title = styled<TP, VPS, Component<TP>>(View)`
color: ${props => props.color}
`
const Index: React.FC = () => {
return <Title color='red'>
Hello World!
</Title>
}
export default Index
Fower
The community has another option Fower,Documentation