JMF Labs logo
Home
Articles

Dynamic imports

Dynamic Imports allows a developer to tell nextjs that a component should be bundled on its own and pulled in once it is being used. This really shines when you have a component that maybe used only on desktop vs mobile. Another great use case is if you have a component only for a certain user level, that most your users aren't. IE: the elite and vip levels vs a regular or guest users.

pages/index.jsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import dynamic from 'next/dynamic'
  
  const DynamicComponent = dynamic(() => import('../components/hello'),
                                    { ssr: false })
  
  function Home() {
    return (
      <div>
        <Header />
        <DynamicComponent />
        <p>HOME PAGE is here!</p>
      </div>
    )
  }
  
  export default Home

Lodash using lodash-es

Lodash is a great package but it is extremely heavy, and most users only use a fraction of the package. Using a package called Lodash-es, which makes lodash easier to tree-shake. This package is still produced by the lodash team.

Another tip we like to use is eslint to enforce the use of lodash-es.

.eslintrc.json

1
2
3
4
5
6
7
8
{
    "no-restricted-imports": ["error", {
      "paths": [{
        "name": "lodash",
        "message": "Please use lodash-es instead of lodash"
      }
    }]
  }

Moment Locales on Nextjs before 11

Moment.js is a time library with locales that help with translations and if you are like many you are probably using luxon. If you are using next 10 or below, then you have to exclude the default locales to make the package smaller. Next 11 already does this so no need to do anything.


@next/bundle-analyzer

This is a webpack bundle analyzer that will allow you to see into the bundles. You can see if different versions of the same package are being included. It is extremely easy to install you just added it to your next.config.js.

.next.config.js

1
2
3
4
5
6

  const withBundleAnalyzer = require('@next/bundle-analyzer')({
    enabled: process.env.ANALYZE === 'true',
  });
  module.exports = withBundleAnalyzer({});
  

Running it this way to build the production version ...

1
ANALYZE=true npx next build

Cache

Another overlooked section is that the url "/_next/static/*" should be a lifetime cache as it is generated using content hash so they can live in cache forever.