NPM 安装依赖
$ npm i linaria
配置项目根目录的 babel.config.js
module.exports = {
presets: [
['taro', {
framework: 'react',
ts: true
}],
'linaria/babel' // 添加到 babel-preset
]
}
之后配置 config/index.js
const config = {
mini: {
webpackChain(chain, webpack) {
// linaria/loader 选项详见 https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md#webpack
chain.module
.rule('script')
.use('linariaLoader')
.loader('linaria/loader')
.options({
sourceMap: process.env.NODE_ENV !== 'production',
})
}
},
h5: {
webpackChain(chain, webpack) {
chain.module
.rule('script')
.use('linariaLoader')
.loader('linaria/loader')
.options({
sourceMap: process.env.NODE_ENV !== 'production',
})
}
}
}
最后在项目根目录新建 linaria.config.js
// linaria 配置详见 https://github.com/callstack/linaria/blob/master/docs/CONFIGURATION.md#options
module.exports = {
rules: [
{
action: require("linaria/evaluators").shaker,
},
{
test: /node_modules[\/\\](?!@tarojs)/,
action: "ignore"
}
]
}
业务代码:
import { styled } from 'linaria/react'
......
render () {
const ViewLogin = styled(View)<{ backgroundImage: string,color:string}>`
background-image:${props => props.backgroundImage};
color: ${props => props.color}
`;
return(
<ViewLogin className='login' color='red' backgroundImage={`url(${APP_CONF.IMG_OSS_PREFIX}/weapp/v1/images/login_bg.png?20211104)`}>
)
}