React 项目中的一种样式管理方式: stylus + react-css-modules

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zeping891103/article/details/84963219

stylus 是一套 css 预处理框架,react项目可以通过 stylus 管理样式文件。react-css-modules 则主要用于实现对样式的模块化引用,stylus 与 react-css-modules 配合使用可以实现一套对react项目的样式管理方案。

在使用 stylus 前需要先对项目进行相应的配置,其步骤如下:

安装Stylus:

安装其所需的依赖包:

$ npm install stylus -S
$ npm install stylus-loader -S

暴露React配置文件:

执行以下脚本把配置文件先暴露出来。

$ npm run eject

执行这段脚本时,会询问您是否确认暴露,因为该过程是不可逆的,选择'Y'即可。若执行发生错误,需要删掉项目中的跟踪文件,如使用HBuilder编译器时会随项目创建时生成.project跟踪文件,同时,最好先把项目全部提交一遍至Git(如果有使用的话),以防过程中发生异常。

修改配置文件:

打开config/webpack.config.dev.js,修改配置如下:

module: {
    strictExportPresence: true,
    rules: [
        ...
         oneOf: [ 
            ...
            {
            test: /\.styl$/, 
            loaders: ['style-loader', 'css-loader', 'stylus-loader']
            },
            {
                // Exclude `js` files to keep "css" loader working as it injects
                // its runtime that would otherwise be processed through "file" loader.
                // Also exclude `html` and `json` extensions so they get processed
                // by webpacks internal loaders.
                exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/, /\.styl$/],
                loader: require.resolve('file-loader'),
                options: {
                    name: 'static/media/[name].[hash:8].[ext]',
                },
            }
         ]
    ]
    ...
}

打开config/webpack.config.prod.js,按上面的办法同样修改一遍,这样build出来的文件.styl文件才会有效。

(小贴士)若想要build后能双击打开index.html就可以看到页面,则把修改publicPath为:

const publicPath = './';

执行以下代码测试效果:

// base.styl
div{
	color: red;
	p {
		color: blue;
	}
}

// App.js
import React from 'react';
import './base.styl';

class App extends React.Component {
	render() {
		return(
			<div>
		      	Hello World!
		      	<p>This is Paragraph!</p>
		     </div>
		);
	}
}

export default App;

启动项目,效果如图所示:

实例地址:https://github.com/smallH/react-stylus.git

这种引用方法有个缺点,所引用的样式将会是全局样式。若想引用成组件私有的样式文件,可以使用react-css-modules。

联合 react-css-modules 和 Stylus实现组件私有样式引用:

初始化

$ npm install react-css-modules -S

打开config/webpack.config.dev.js,修改配置如下:

{
	test: /\.styl$/,
	loaders: [
		'style-loader',
		'css-loader?modules&localIdentName=[name]-[hash:base64:5]',
		'stylus-loader'
	]
},
{
	// Exclude `js` files to keep "css" loader working as it injects
	// its runtime that would otherwise be processed through "file" loader.
	// Also exclude `html` and `json` extensions so they get processed
	// by webpacks internal loaders.
	exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/, /\.styl$/],
	loader: require.resolve('file-loader'),
	options: {
		name: 'static/media/[name].[hash:8].[ext]',
	},
}

使用:

import React from 'react'
import styles from './index.styl'
import CSSModules from 'react-css-modules'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as AllActions from '@/reducers/Auth/actions'
import PropTypes from 'prop-types'

class Login extends React.Component {
	static propTypes = {
		actions: PropTypes.object.isRequired
	}

	constructor(props) {
		super(props)
		this.state = {}
	}

	visitor = () => {
		this.props.actions.signIn("");
		this.props.history.push({
			pathname: '/home/welcome'
		})
	}

	manager = () => {
		this.props.actions.signIn("API-TOKEN20181214");
		this.props.history.push({
			pathname: '/home/welcome'
		})
	}

	render() {
		return(
			<div id="login" styleName="login">
				<div styleName="title">欢迎使用 react-redux-axios 前端框架</div>
				<div styleName="nav">
					<div styleName="btn" onClick={this.visitor}>游客</div>
					<div styleName="btn manager" onClick={this.manager}>管理员</div>
				</div>
			</div>
		);
	}
}

// 同样实现propTypes效果
//Login.propTypes = {
// 	actions: PropTypes.object.isRequired
//}

const CSSLogin = CSSModules(Login, styles, {
	allowMultiple: true
});

const mapDispatchToProps = (dispatch, ownProps) => ({
	actions: bindActionCreators(AllActions, dispatch)
})

export default connect(null, mapDispatchToProps)(CSSLogin)

样式文件:

// index.styl

.login{
	.title {
	text-align: center;
	font-size: 46px;
	font-weight: bold;
	margin-top: 200px;
	}
	
	.nav {
		display: flex;
		margin-top: 50px;
		justify-content: center;
		align-items: center;
	}
	
	.btn {
		min-width: 140px;
		text-align: center;
		font-size: 24px;
		cursor: pointer;
		border-radius: 30px;
		background-color: #009688;
		color: white;
		width: fit-content;
		padding: 10px;
		margin-top: 0px;
	}
	
	.manager {
		margin-left: 20px;
		color: gray;
		background-color: transparent;
		border: solid 1px #009688;
	}
}

以上是react项目中样式管理的其中一种方式,希望能对大家开发react项目针对样式问题上有所参考作用,一起加油!

猜你喜欢

转载自blog.csdn.net/zeping891103/article/details/84963219