在React脚手架中配置使用stylus

在React脚手架中配置使用stylus

创建一个项目

我们此次使用react脚手架工具创建一个空白的项目,具体为:

1
$ create-react-app with-stylus

创建完空白项目后,我们为项目添加一个我们自己的Remote地址(可选)。

1
2
$ git remote add origin GIT_URL
$ git push -u origin master

导出配置项

1
$ yarn eject

中间会有一次交互,提醒此操作是永久性操作,不可回退,选择Y即可。

修改配置

修改的文件为:config/webpack.config.js 此目录只有在执行过eject之后才会出现。

  1. 先将styl文件添加到file-loaderexclude列表中,也就是说,我们不直接用fileloader去解析styl
    文件,而是需要继续往下找到对应的loader
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
loader: require.resolve('file-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$/
],
options: {
name: 'static/media/[name].[hash:8].[ext]'
}
}
  1. styl文件添加到loader规则中,具体位置为:return->module->rules
1
2
3
4
{
test: /\.styl$/,
loaders: ['style-loader', 'css-loader', 'stylus-loader']
},

测试

jsx文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import React from 'react'
import './App.styl'

function App() {
return (
<div className="App">
<div className="test-stylus">
<div className="text-box">123123</div>
</div>
</div>
)
}

export default App

styl文件

1
2
3
4
5
6
7
8
9
10
11
12
.test-stylus 
width: 100px
height: 100px
background black
margin-top: 50px
padding 10px
margin-left: 50px
.text-box
background: white
color black
width 50px
height 50px

最终效果

```

在React脚手架中配置使用stylus

https://www.borgor.cn/posts/1180e59c.html

作者

Cyrusky

发布于

2020-01-27

更新于

2024-11-18

许可协议

评论