Dynamic import with not bundled file

随声附和 提交于 2019-12-04 11:06:57

I finally came up with a solution.

LoadJS library. You can use $script also.

Library project (external components): index.js:

import App from './App';

export const MyComponentLib = {
   App
};

App.jsx:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

export default class App extends Component {
   render() {
      return (
         <div className="App">
             <header className="App-header">
                 <img src={logo} className="App-logo" alt="logo" />
                 <h1 className="App-title">Welcome to React</h1>
             </header>
             <p className="App-intro">
                 To get started, edit <code>src/App.js</code> and save to reload.
             </p>
         </div>
      );
   }
}

In the library's webpack config file (production), added:

libraryTarget: 'umd',

Main project file (main.js):

componentWillReceiveProps(nextProps){
    if(nextProps.pagesData && this.props.pagesData !== nextProps.pagesData && nextProps.pagesData.get('cards').count() > 0){

        // Getting all asyncCards from state
        let currentCards = cloneDeep(this.state.asyncCards);

        // Immutable "get" function - getting cards from nextProps
        nextProps.pagesData.get('cards').forEach(card => {

            // Getting card_type, which in this case is the filename
            let cardType = card.get('card_type');

            // Do we have this card already in the state object?
            if(!hasIn(currentCards, cardType)) {

                // AsyncLoading the card file
                loadjs(`/custom/1/${cardType}.js`, cardType, {
                    success: () => {

                        // Cloning App function (the component)
                        currentCards[cardType] = window.MyComponentLib.App.bind({});

                        this.setState({
                            asyncCards: currentCards
                        })
                    }
                })
            }
        })
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!