由create-react-app的react项目使用局部css

为什么webpack项目中使用局部css

在项目中,尤其是大项目中,很可能因为使用相同的css,在vue中可以直接在style中加入scope属性,而在create-react-app的react项目怎么实现这种局部的style呢

通过style-loader实现局部css

第一种方式通过style-loader的modules属性

暴露出webpack配置 如果暴露过了 省略此步骤

npm run eject

修改配置

// config > webpack.config.dev.js


// style files regexes
const cssRegex = /\.css$/;
const useable = /\.use(able)?\.css$/;  // 添加 匹配css
const cssModuleRegex = /\.module\.css$|\.use(able)?\.css$/; 
const useableCssModuleRegex = /\.module\.css$/;   // 添加适合use.css或者useable.css结尾的文件的 排除文件名



 {
    test: cssRegex,
    exclude: cssModuleRegex,
    use: getStyleLoaders({
      importLoaders: 1,
    }),
  },
 {
    test: useable,
    exclude: useableCssModuleRegex,
    use: getStyleLoaders({
      importLoaders: 1,
      modules: true  // 添加到这里
    }),
  },

改完配置需要重新编译

 npm strat

css 注意在配置中配置了正则,值匹配名带use.css或者useable.css为结尾的文件

//  style.use.css
.box {
    background: red;
}

组件中使用

import React, {Component} from 'react';
import style from './style.use.css'

export default class Test extends Component {
    render() {
        return(
            <div className = {style.box}>
                <div>
                    {'测试'}
                </div>
            </div>
        )
    }
}

最终class被修改只在此组件中使用,在组件中就可以用这种方式来设置局部的css了

第二种方式

通过这种方式,不是真正的设置了局部变量,而是让style只在这个组件渲染的时候,将style添加到页面中,组件销毁之后卸载组件用的style
这种方式看起来貌似没有第一种好,但是这种方式使用起来不需要用className = {style.className},不需要任何改动,直接用 className = 'className'就可以

首先也是暴露出webpack配置 如果暴露过了 省略此步骤

npm run eject
// config > webpack.config.dev.js

修改配置
// style files regexes
const cssRegex = /\.css$/;
const useable = /\.use(able)?\.css$/;  // 添加 匹配use.css或者useable.css结尾的文件
const cssModuleRegex = /\.module\.css$|\.use(able)?\.css$/; // 这里也需要修改 需要让普通名称的css文件的loader覆盖
const useableCssModuleRegex = /\.module\.css$/;   // 添加适合use.css或者useable.css结尾的文件的 排除文件名


// 添加一个getUseableLoaders
const getUseableLoaders = (cssOptions, preProcessor) => {
  const loaders = [
    require.resolve('style-loader/useable'),
    {
      loader: require.resolve('css-loader'),
      options: cssOptions,
    },
    {
      // Options for PostCSS as we reference these options twice
      // Adds vendor prefixing based on your specified browser support in
      // package.json
      loader: require.resolve('postcss-loader'),
      options: {
        // Necessary for external CSS imports to work
        // https://github.com/facebook/create-react-app/issues/2677
        ident: 'postcss',
        plugins: () => [
          require('postcss-flexbugs-fixes'),
          require('postcss-preset-env')({
            autoprefixer: {
              flexbox: 'no-2009',
            },
            stage: 3,
          }),
        ],
      },
    },
  ];
  if (preProcessor) {
    loaders.push(require.resolve(preProcessor));
  }
  return loaders;
};
   ...
   ...
   {
    test: cssRegex,
    exclude: cssModuleRegex,
    use: getStyleLoaders({
      importLoaders: 1,
    }),
  },
  { // 添加loader
    test: useable,
    exclude: useableCssModuleRegex,
    use: getUseableLoaders({
      importLoaders: 1,
    }),
  },
  ...
  ...

改完配置需要重新编译

 npm strat

css 注意在配置中配置了正则,值匹配名带use.css或者useable.css为结尾的文件

//  style.use.css
.box {
    background: red;
}

组件中使用

import React, {Component} from 'react';
import style from './style.use.css'

export default class Test extends Component {
    render() {
        return(
            <div className = 'box'>
                <div>
                    {'测试'}
                </div>
            </div>
        )
    }
}

这样就之后再加载此组件中 style.use.css 才会被引用

posted @ 2018-12-19 23:48  SSS小龙SSS  阅读(3417)  评论(0编辑  收藏  举报