动态导入未绑定文件
问题描述:
我有一个与Webpack捆绑在一起的React项目。动态导入未绑定文件
我有一个组件,我希望它动态地呈现组件。就我而言,组件的路径来自道具。
此外,这些组件未捆绑在我的项目.js文件中;它们是外部React组件/库文件。
我已经试过了动态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 });
})
}
}
这不起作用,因为进口需要一个静态路由。
然后我试着要求:
let dynamicComponent = require(cardType);
不工作,因为(我认为)的WebPack试图找到它进入主束。
这甚至有可能吗?
更新:它看起来像这样可以工作(cardType是 'index.js' - 一个阵营成分):
import(`/home/user/_apps/module/react-module/lib/${cardType}`)
的WebPack创建一个不同的束(块)包括index.js的代码和所有它的依赖。
但这并不能真正解决我原来的问题。
编辑2:从上面的导入实际上忽略了最后一个var,并且Webpack使得/ lib中的每个文件都成为块。
答
我终于想出了一个解决方案。
库项目(外部元件): 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>
);
}
}
在图书馆的WebPack配置文件(生产)补充说:
libraryTarget: 'umd',
主项目 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
})
}
})
}
})
}
}