Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

406
Views
How to use dynamic imports conditionally?

I have a React app created with CRA. The app is built for two environments: website and browser extension which replaces a speed dial. Whereas it is nice to use dynamic imports for website, it would be good to bundle some pages into main chunk, so that there is no splashscreen when opening a new tab.

Do you have any idea how to conditionally use dynamic imports basing on environment variable? I've tried the following approach:

import WebsktopEager from 'pages/app/Websktop';
const WebsktopLazy = lazy(() => import('pages/app/Websktop'));

const Websktop = process.env.REACT_APP_TARGET === 'extension' ? WebsktopEager : WebsktopLazy;

I expected that webpack's tree shaking would remove dead code basing on the condition, but WebsktopEager is still bundled into a main chunk, even though process.env.REACT_APP_TARGET !== 'extension'.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Based on your code, cherry-picked bundling won't happen just because process.env.REACT_APP_TARGET === 'extension' is present as you expected; because it'll only work on runtime!

So CRA will be optimistic while bundling the code, and will bundle eager imports as well.

What you can do is have two separate entry files, of sorts: For eg -

main.eager.js // containing your eager imports
main.lazy.js // containing your dynamic/lazy imports

Now have a custom webpack config to separately build the projects based on any condition, environment variables that you'd like to use. And the entry point for those bundles can be differentiated based on the above said files

But ofcourse custom webpack config would require you to execute npm run eject command. So take a look at articles about that online

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!