Yes
Set up a project similar to https://github.com/penx/cra-code-splitting-exports
Specifically, say you have an index file for your components:
import Component1 from './component-one'
import Component2 from './component-two'
export {Component1, Component2};
Then in your application, you import Component1 in the main App and import Component2 via React.lazy/import()
I would expect the code from /src/components/component-two.js to be included in the lazy loaded chunk.
The code from /src/components/component-two.js is included on initial page load because it comes from /src/components/index.js so is included in the same bundle as src/components/component-one.js.
In the case of local modules, you can import from the module directly instead of going via an index file. Unfortunately you don't always have this option if you want to lazy load part of a dependency:
i.e.
if you have the following on app load:
import { someUtil } from 'my-library'
And the following is in a component that is lazy loaded:
import { aMuchLargerUtil } from 'my-library'
Then I would not want aMuchLargerUtil to be included in the initial bundle.
git clone [email protected]:penx/cra-code-splitting-exports.git
cd cra-code-splitting-exports
yarn && yarn build
serve -s build
When you import ./components in App.js, webpack loads the whole module and evaluates it.
The only "issue" I can see here is why webpack can't tree-shake ComponentTwo, since it isn't used in main chunk.
I found a "documented hack".
Create a package.json file in ./components directory with the following contents:
{
"sideEffects": false
}
ah that sounds good. I guess it means if ./components was actually a node module in dependencies, I could add it in to the package.json there... will give it a go.
it worked! Thanks <3
Demo of it working, including for CSS modules, here https://penx.github.io/govuk-frontend-react-example/
Most helpful comment
I found a "documented hack".
Create a
package.jsonfile in./componentsdirectory with the following contents: