javascript中的require和import

模块化的代码在各种语言的程序开发中,都是被广泛采纳的最佳实践

  • 增加代码的易读性。一般超过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 (
      
); } } 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 (
      
{this.props.name}
) } } 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 {...

你可能感兴趣的:(javascript中的require和import)