2017-10-20 19 views
4

나는 Webpack에 번들로 제공되는 React 프로젝트를 보유하고 있습니다.번들 파일이없는 동적 가져 오기

구성 요소를 동적으로 렌더링하려는 구성 요소가 있습니다. 필자의 경우 구성 요소의 경로는 소품에서 비롯됩니다.

또한이 구성 요소는 내 프로젝트 .js 파일에 번들로 제공되지 않습니다. 그것들은 외부의 React components/libaries입니다. 나는 동적 ES6 가져 오기를 시도했습니다

:

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

가져 오기가 고정 경로를 필요로하기 때문에이 작동하지 않습니다. 그럼 난과 시도했습니다

이 필요합니다 (I 가정) 때문에

let dynamicComponent = require(cardType); 

작동하지 않는 웹팩은 기본 번들로를 찾습니다.

이렇게해도 될까요?

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

웹팩 다른 번들 (덩어리)를 생성하는 index.js의 코드를 포함 : - :

업데이트이 작동 할 수처럼 보이는 (A 반작용 구성 요소에 cardType는 '하는 index.js'입니다) 모든 것이 종속됩니다.

하지만 내 원래의 질문은 실제로 해결되지 않습니다.

편집 2 : 위의 가져 오기는 실제로 마지막 var를 무시하고 Webpack은/lib 안에있는 모든 파일의 청크를 만듭니다.

답변

2

마침내 해결책이 생겼습니다.

LoadJS 라이브러리. $script도 사용할 수 있습니다.

라이브러리 프로젝트 (외부 부품) : 하는 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> 
    ); 
    } 
} 

, 추가 :

libraryTarget: 'umd', 

주요 프로젝트 파일 (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 
         }) 
        } 
       }) 
      } 
     }) 
    } 
}