Home >Web Front-end >JS Tutorial >Tutorial on how to dynamically load ES6 code components

Tutorial on how to dynamically load ES6 code components

零下一度
零下一度Original
2017-05-13 10:48:112238browse

This article mainly introduces the detailed explanationReactUsing require.ensure() in development to load ES6 components on demand, which is of great practical value. Friends in need can refer to it

First introduce the dynamic loading function:

require.ensure([], (require)=>{
  let A = require('./a.js').default;
})

If you want to dynamically load an es6 code component, it is not possible to directly require an es6 style component, because general language compilation tools (such as babel), Directly requiring an es6-style component is not supported.

Then there is a way to solve it: add a sentence at the bottom of the component written in es6 mode: module.exports = YouclassName;

import React, {Component} from 'react';

export default class Father extends Component {
  constructor (props)=>{
    super();
    this.state = {
      currentComponent:null
    }
  }

  doSomething = () => {
    require.ensure(['./app2'], (require) => {
      const Comp = require('./app2');
      this.setState({
        currentComponent:<Comp />
      })
    })
  }

  render () {
    return (
      <p>
        <span onClick={this.doSomething} >
          点击后,按需加载模块~
        </span>
        {this.state.currentComponent}
      </p>
    )
  }
}

app2

import React,{Component} from &#39;react&#39;;
export default class Hello extends Component {
  render () {
    return (
      <p>你好,祝你幸福,再见~</p>
    )
  }
}

module.exports= Hello;

Because in require require() is used in .ensure() to introduce the module, so the component must be exported using module.exports;

[Related recommendations]

1. Special recommendation: "php Programmer Toolbox" V0.1 version download

2 . Free js online video tutorial

3. php.cn Dugu Jiujian (3) - JavaScript video tutorial

The above is the detailed content of Tutorial on how to dynamically load ES6 code components. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn