【问题标题】:How to find unused style definitions in React?如何在 React 中找到未使用的样式定义?
【发布时间】:2017-08-14 18:53:25
【问题描述】:

有没有办法在基于 React 的项目中自动找到未使用的样式定义,就像这个例子一样?

之前:

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

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

之后:

开发者更改了样式,不再需要“名称”。这种死气沉沉的代码怎么能自动找到呢?

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>;
  }
});

【问题讨论】:

  • 你试过 ESLint 吗?我不确定它是否会检测到这个特定示例,但它通常有助于识别未使用的变量和定义。
  • @MartinMihaylov 对 styles.name 的引用在 JSX/HTML 中,所以我很确定 Linter 将无法捕捉到它 =/
  • CSS 模块看起来很有前途medium.com/@pioul/…

标签: css reactjs react-jsx jsx


【解决方案1】:

可能的解决方案

1) helpers.js

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

2) 组件.js

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 2017-11-12
    • 1970-01-01
    • 2019-05-28
    • 2021-04-02
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    相关资源
    最近更新 更多