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開發環境。css

打開http://localhost:3000/ 查看html

環境配置:

生成項目後,腳手架爲了「優雅」... ...隱藏了全部的webpack相關的配置文件,此時查看myapp文件夾目錄,會發現找不到任何webpack配置文件。執行如下命令:node

yarn eject

再查看myapp 文件夾,能夠看到完整的項目結構:react

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

按需引入webpack

爲減小打包後體積以及方便書寫,可用babel-plugin-import插件,配置在config目錄下,git

webpack.config.dev.js 和 webpack.config.prod.js文件,這裏以webpack.config.dev.js舉例,github

webpack.config.prod.js同樣配置便可:web

// 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,
            },
          },

引入模塊以下:npm

// 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 不能混用,看知乎大神說 能夠json

針對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);
相關文章
相關標籤/搜索