Dynamic import with not bundled file

試著忘記壹切 提交于 2019-12-21 18:39:21

问题


I have a React project bundled with Webpack.

I have a component that I want it to render components Dynamically. In my case, the path of the component comes from props.

Also, these components are not bundled in my project .js file; they are external React components/libaries.

I've tried the Dynamic ES6 import:

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

        // Getting the first card from the Immutable object
        let card = nextProps.pagesData.getIn(['cards', 0]);

        // Getting the cardType which can be: '/path/index.js'
        let cardType = card.get('card_type');

        // ES6 Dynamic import
        import(cardType)
            .then(module => {
                 this.setState({ asyncCard: module.default });
             })
    }
}

This doesn't work because import needs a static route.

Then I've tried with require:

let dynamicComponent = require(cardType);

Which doesn't work because (I assume) Webpack tries to find it into the main bundle.

Is this even possible to do?

Update: It looks like this can work (cardType is 'index.js' - a React component):

import(`/home/user/_apps/module/react-module/lib/${cardType}`)

Webpack creates a different bundle (chunk) including the code of index.js and all it's dependencies.

But this doesn't really solve my original question.

Edit 2: The import from above actually ignores the last var and Webpack makes chunks of every file inside /lib.


回答1:


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
                        })
                    }
                })
            }
        })
    }
}


来源:https://stackoverflow.com/questions/46845792/dynamic-import-with-not-bundled-file

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