模块化的代码在各种语言的程序开发中,都是被广泛采纳的最佳实践
- 增加代码的易读性。一般超过200行的代码,读起来就很费劲了
- 提高程序加载速度。首次加载程序时,只加载需要的模块。
在Javascript中,模块化是通过module来实现的。在ES2015之前的语法是require/export,ES2015及以后的语法变成了import/export
ES2015之前
//app.js
var React = require('react');
var Component = React.Component;
require('./App.css');
var Color = require('./Shapes');
class App extends Component {
render() {
return (
<div className="App">
<div className="colors">
<Color name="red"/>
<Color name="green"/>
<Color name="blue"/>
</div>
</div>
);
}
}
module.exports = App;
//Shapes.js
var React = require('react');
var Component = React.Component;
class Color extends Component {
render() {
const divStyle = {
backgroundColor: this.props.name,
color: 'white',
fontSize: '20px',
height: '100px',
width: '100px'
}
return (
<div style={divStyle}>{this.props.name}</div>
)
}
}
module.exports = Color;
export多个对象
//Shapes.js
module.exports = {
Color: Color,
Animal: Animal
}
//App.js
var {Color} = require('./Shapes');
var {Animal} = require('./Shapes');
ES2015及以后
//App.js
import React, {Component} from 'react';
import './App.css';
import {Color, Animal} from './Shapes';
...
export default App;
//Shapes.js
import React, {Component} from 'react';
export class Color extends Component {...
export class Animal extends Component {...
网友评论