如何在React中找到未使用的样式定义?

时间:2017-03-22 15:00:27

标签: css css3 reactjs react-jsx jsx

有没有办法在基于React的项目中自动查找未使用的样式定义,如本示例所示?

之前:

const styles = StyleSheet.create({
  name: {
    color: '#e5e5e5'
  }
});

const Hello = React.createClass({
  render: function() {
    return <Text style={styles.name}>Hello {this.props.name}</Text>;
  }
});

后:

开发人员改变了风格,&#34;名称&#34;不再需要了。如何自动找到这种死机代码?

const styles = StyleSheet.create({
  name: { // Redundant now!
    color: '#e5e5e5'
  },
  foo: {
    color: '#e2e3b5'
  }
});

const Hello = React.createClass({
  render: function() {
    return <Text style={styles.foo}>Hello {this.props.name}</Text>;
  }
});

1 个答案:

答案 0 :(得分:0)

可能的解决方案

1)helpers.js

&#13;
&#13;
// helpers.js
import ReactTestUtils from 'react-addons-test-utils'

export function unusedStyles(component, styles) {
    const renderer = ReactTestUtils.createRenderer();
    renderer.render(component);
    const rendered = renderer.getRenderOutput();
    const myStylesInUse = stylesInUse(rendered);
    return filterStyles(styles, myStylesInUse);
}

function stylesInUse(el) {
    var arr = [];

    function go(el) {
        const { children, style } = el.props;
        const childrenType = Object.prototype.toString.call(children);
        style && arr.push(style)
        if(childrenType === '[object Object]') {
            go(children);
        } else if(childrenType === '[object Array]') {
            children.forEach(child => { go(child) });
        }
    }

    go(el);

    return arr;
}

function filterStyles(styles, compStyles) {
    const arr = [];

    for(let key in styles) {
        const found = compStyles.find(item => item === styles[key]);
        if(!found) arr.push(key)
    }

    return arr;
}
&#13;
&#13;
&#13;

2)Component.js

&#13;
&#13;
import { unusedStyles } from './helpers';

const styles = StyleSheet.create({
  one: {
    color: 'one'
  },
  two: {
    color: 'two'
  },
  three: {
    color: 'three'
  }
});

class Hello extends Component {

  render() {
    return (
      <div style={styles.one}>
        <div style={style.two}>Hello!</div>
      </div>
    )
  }

}

// here you can test your styles
const myUnusedStyles = unusedStyles(<Hello />, styles)
// => ['three']

if(myUnusedStyles.length) {
  console.log('UNUSED STYLES DETECTED', myUnusedStyles);
}

export default Hello
&#13;
&#13;
&#13;