SoFunction
Updated on 2025-04-07

How to use loading es6-style components in react development

The practical babel should be loadable on the browser side, and there was a default before:

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

The following method is also OK, but it is relatively low and can be invalid:

1. Question asked: Want to load es6-style modules?

2. Problems arise: The import method itself is a static design method. If the required input is the commonjs module or amd, it will be fine, but the project only wants es6 writing style, is it OK?

Unfortunately: general language compilation tools (such as babel) do not support directly requiring an es6-style React component.

what to do? ?

3. React code segmentation method:

React code segmentation is commonly used to use router, but it is not intended to be router-based. You can use it to load on demand

react's api is here:/docs/

There are no instances in the document, and at this stage, most programs have completely followed the es6 style code.

So how can the es6 module be able to pass require?

Let’s look at the conclusion first: add a sentence at the bottom of the module written in es6 mode = yourclassName

For example: = Hello;

4. Code example:

1) The Container module is as follows:

import React, {Component} from 'react';
export default class Container extends Component {
  constructor() {
    super();
     = {
      currentComponent: null
    }
  }

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

  render() {
    return (
      <div>
        &lt;span onClick={} style={{border: "1px solid #000"}}>After clicking, load the following module as needed</span>        {}
      &lt;/div&gt;
    )
  }
}

2) The app2 module is as follows

Note: Add a sentence at the bottom of the module written in es6 mode: = Hello;

Or app2 can be written directly in accordance with the commonjs specification or the amd and cmd specifications.

import React from 'react'
export default class Hello extends  {
  render(){
    return (
      &lt;div&gt;Hello&lt;/div&gt;
    )
  }
}
//warning: This sentence must be added because the required module is used in it. = Hello;

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.