Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: Load .less only when component is used

Tags:

reactjs

less

I am probably missing a verry basic understanding of loading less files in ReactJS, but I am unable to solve the following issue.

I have created components and created less files for each of them, for example:

import * as React from 'react';
import Row from 'antd/lib/row';
import Col from 'antd/lib/col';
import { NavLink } from 'react-router-dom';
import '../styles/how-it-works-styles.less';
import Icon from 'antd/lib/icon';


class HowItWorksComponent extends React.PureComponent<Props> {

  public constructor(props: Props) {
      super(props);
  }

  public render() {
    return (
        <Row className={'steps-row'}>

Now when I load a page where this component is not at all used, the less file is stilling being loaded into the dom. Could someone explain why this is happening and how i can prevent this from happening?

like image 982
apfz Avatar asked Jun 13 '26 20:06

apfz


1 Answers

Your problem is not really about less, but a general problem of how to bundle a web app optimally. Since you're not providing your main app component or your webpack config (assuming you're using webpack for bundling), I obviously don't know the details of your setup. In general however, the standard configuration is to bundle all the components and other imports reachable from the entry point file into one big file. The fact that you use react router or similar to split your app into "pages" doesn't change this, as react router only affects which components are rendered when, not the bundling.

If you need to split your app into multiple bundles (which IMO requires a relatively large app to consider) you can use dynamic imports to make some of your components "Loadable". This means they will be placed in a separate bundle which is only loaded as needed. There is a tutorial in the react router documentation on how to set this up: https://reacttraining.com/react-router/web/guides/code-splitting

like image 145
Jonas Høgh Avatar answered Jun 17 '26 11:06

Jonas Høgh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!