create-react-app+antd+react-css-modules配置

快速开始:

npm install -g create-react-app       /* 安装create-react-app */

npm install -g create-react-app       /* 安装yarn */

create-react-app myapp                /* 使用命令创建应用,myapp为项目名称 */

cd myapp                              /* 进入目录 */

yarn start                            /* 启动项目 */

按以上执行,即可快速创建React开发环境。

打开http://localhost:3000/ 查看

环境配置:

生成项目后,脚手架为了“优雅”... ...隐藏了所有的webpack相关的配置文件,此时查看myapp文件夹目录,会发现找不到任何webpack配置文件。执行以下命令:

yarn eject

再查看myapp 文件夹,可以看到完整的项目结构:

myapp/

    node_modules/

    package.json

    .gitignore

    config/

        paths.js

        polyfills

        env.js

        webpack.config.dev.js /* 开发环境配置文件 */

        webpack.config.prod.js /* 生产环境配置文件 */

    public/

        index.html   /* 入口html文件 */

    scripts/

        build.js

        start.js

        test.js

    src/

        App.js

        index.js    /* 主入口文件 */

antd配置

yarn add antd babel-plugin-import

按需引入

为减少打包后体积以及方便书写,可用babel-plugin-import插件,配置在config目录下,

webpack.config.dev.js 和 webpack.config.prod.js文件,这里以webpack.config.dev.js举例,

webpack.config.prod.js一样配置即可:

// Process JS with Babel.
          {
            test: /\.(js|jsx)$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: {
              // 改动: 添加 antd 按需加载文件处理插件
              plugins: [
                //['react-html-attrs'],//添加babel-plugin-react-html-attrs组件的插件配置
                // 引入样式为 css
                ['import', { libraryName: 'antd', style: 'css' }],
                // 改动: 引入样式为 less
                //  ['import', { libraryName: 'antd', style: true }],
              ],
              // This is a feature of `babel-loader` for webpack (not Babel itself).
              // It enables caching results in ./node_modules/.cache/babel-loader/
              // directory for faster rebuilds.
              cacheDirectory: true,
            },
          },

引入模块如下:

 // scr/App.js
  import React, { Component } from 'react';
- import Button from 'antd/lib/button';
+ import { Button } from 'antd';
  import './App.css';

CSS Modules 配置

antd 和 css modules 不能混用,看知乎大神说 可以

针对antd的css 单独写一条loader的规则,不开启 css modules。

使用 exclude 和 include 配置

配置在config目录下,同样修改配置 webpack.config.dev.js 文件

          {
            test: /\.css$/,
            exclude: /node_modules|antd\.css/,
            use: [
              require.resolve('style-loader'),
              {
                loader: require.resolve('css-loader'),
                options: {
                  importLoaders: 1,
                  // 改动
                  modules: true,   // 新增对css modules的支持
                  localIdentName: '[name]__[local]__[hash:base64:5]', //
                },
              },
              {
                loader: require.resolve('postcss-loader'),
                options: {
                  // Necessary for external CSS imports to work
                  // https://github.com/facebookincubator/create-react-app/issues/2677
                  ident: 'postcss',
                  plugins: () => [
                    require('postcss-flexbugs-fixes'),
                    autoprefixer({
                      browsers: [
                        '>1%',
                        'last 4 versions',
                        'Firefox ESR',
                        'not ie < 9', // React doesn't support IE8 anyway
                      ],
                      flexbox: 'no-2009',
                    }),
                  ],
                },
              },
            ],
          },
          //
          {
            test: /\.css$/,
            include: /node_modules|antd\.css/,
            use: [
              require.resolve('style-loader'),
              {
                loader: require.resolve('css-loader'),
                options: {
                  importLoaders: 1,
                  // 改动
                  // modules: true,   // 新增对css modules的支持
                  // localIdentName: '[name]__[local]__[hash:base64:5]', //
                },
              },
              {
                loader: require.resolve('postcss-loader'),
                options: {
                  // Necessary for external CSS imports to work
                  // https://github.com/facebookincubator/create-react-app/issues/2677
                  ident: 'postcss',
                  plugins: () => [
                    require('postcss-flexbugs-fixes'),
                    autoprefixer({
                      browsers: [
                        '>1%',
                        'last 4 versions',
                        'Firefox ESR',
                        'not ie < 9', // React doesn't support IE8 anyway
                      ],
                      flexbox: 'no-2009',
                    }),
                  ],
                },
              },
            ],
          },

下面是一个 antd 的 Button 和自己写的CSS Modules 使用小例子:

import React, { Component } from 'react';
import { addRecipe } from '../actions';
import { Button } from 'antd';
import styles from './App.css'

class App extends Component {
  state = {
    calendar: null
  }
  componentDidMount() {
    const { store } = this.props // 从props获取store
    store.subscribe(() => { // 订阅 redux store 中发生的任何变化
      this.setState(() => ({ // 有任何变化需要调用 setState
        calendar: store.getState() // 将从store中获取state将它放入本地组件state中
      }))
    })
  }
  submitFood = () => {
    this.props.store.dispatch(addRecipe({//store.dispatch调用addRecipe动作生成器
      day: 'monday',
      meal: 'breakfast',
      recipe: {
        label: this.input.value
      }
    }))
    this.input.value = ''//将输入值重置为一个空的字符串
  }
  render() {
    return (
      <div>
        <input
          type='text'
          ref={(input)=>this.input = input}
          placeholder="Monday's Breakfast"
        />
        <Button type="primary" onClick={this.submitFood}>Submit</Button>

        <pre className={styles.input}>Monday's Breakfast:{this.state.calendar&&this.state.calendar.monday.breakfast}</pre>

      </div>
    );
  }
}

export default App

参考学习 CSS Modules阮一峰老师写的用法教程

这里简单使用下 react-css-modules,代码如下:

import React, { Component } from 'react';
import { addRecipe } from '../actions';
import { Button } from 'antd';
import CSSModules from 'react-css-modules'
import styles from './App.css'

class App extends Component {
  state = {
    calendar: null
  }
  componentDidMount() {
    const { store } = this.props // 从props获取store
    store.subscribe(() => { // 订阅 redux store 中发生的任何变化
      this.setState(() => ({ // 有任何变化需要调用 setState
        calendar: store.getState() // 将从store中获取state将它放入本地组件state中
      }))
    })
  }
  submitFood = () => {
    this.props.store.dispatch(addRecipe({//store.dispatch调用addRecipe动作生成器
      day: 'monday',
      meal: 'breakfast',
      recipe: {
        label: this.input.value
      }
    }))
    this.input.value = ''//将输入值重置为一个空的字符串
  }
  render() {
    return (
      <div>
        <input
          type='text'
          ref={(input)=>this.input = input}
          placeholder="Monday's Breakfast"
        />
        <Button type="primary" onClick={this.submitFood}>Submit</Button>

        <pre styleName='input'>Monday's Breakfast:{this.state.calendar&&this.state.calendar.monday.breakfast}</pre>

      </div>
    );
  }
}

export default CSSModules(App, styles);

主要差别在于:

+ import CSSModules from 'react-css-modules'

- <pre className={styles.input}>
+ <pre styleName='input'>

- export default App
+ export default CSSModules(App, styles);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值