2017-03-22 15 views
1

この例のように、Reactベースのプロジェクトで未使用のスタイル定義を自動的に見つける方法はありますか?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>; 
    } 
}); 
+0

ESLintを試しましたか?私はこの特定の例を検出するかどうかはわかりませんが、一般的に未使用の変数と定義を特定するのに役立ちます。 –

+0

@MartinMihaylov styles.nameがJSX/HTMLになっているので、Linterがそれを捕まえることができないと確信しています。/ – Timo

+0

CSSモジュールは有望ですhttps://medium.com/@pioul/modular -css-with-react-61638ae9ea3e#.gyk7kq6fl – Timo

答えて

0

解決策

1)

// 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)Component.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
をhelpers.js

関連する問題