babel-plugin-transform-react-jsx-img-import
babel-plugin-transform-react-jsx-img-import copied to clipboard
Include Support for Dynamic Generated Filepaths in JSX
Thanks for the great plugin. One potential improvement would be to add support for dynamic data in JSX. Specifically the following code that is not caught by this plugin:
render() {
const {details} = this.props;
return (
<Col xs={3}>
<div styleName={this.isActive(details.attributes)}>
<img styleName="blockShoe" src={`../../${details.image}`} />
</div>
</Col>
);
}
Thanks again and let me know if there is anything that I can do to help or if this is just a bug within my code.
Hi Roy, Definitely this is not a bug, the plugin only process img with literal sources, as the transformation occurs in compile time ( not in runtime ) it is impossible to evaluate an expression. In other hand, the plugin generate the needed imports and imports in ES6 are meant for static analysis. Anyways , I know that webpack use something called contexts for process dynamic requires ( not imports ) so we can tag this as a enhancement and make some further research about whether this technique is applicable here or not.
Sounds great. Thanks for the detailed response and background on what might be possible as an enhancement I'm the future.
I'd love to see this enhancement happen. Must admit that I don't know very much about how it might work in other packers - but webpack indeed supports dynamic requires. Consider the following dummy React component:
class MyComp extends React.PureComponent {
static propTypes = {
num: React.PropTypes.number.isRequired,
};
render() {
const { num } = this.props;
const img = require(`./image${num}.jpg`);
return (<div>
<h1>Simple src</h1>
<img src="./image2.jpg" />
<h1>With explicit require</h1>
<img src={img} />
<h1>With string src attribute value</h1>
<img src={`./image${num}.jpg`} />
</div>)
}
}
With your the jsx-img-import transform enabled, the first image works exactly as expected. The 2nd image works, regardless of the transfform, and the third image would work - if this enhancement goes through.
(ps & OT: I'm looking for a similar transform for jade/pug)
Hi, any news on this? This would indeed be a neat enhancement