Skip to content

SSR and ES6

To support every modern front end environment, the dnb-ui-lib supports different module formats:

  • ESM with ES5 (default)
  • ES with ES6
  • CJS with ES5
  • UMD with ES5

Default module format

The dnb-ui-lib uses ESM as the default module format. This allows us to more easily and by default tree shaking support:

// Imports only the code needed for the button
import { Button } from 'dnb-ui-lib'
import { Button } from 'dnb-ui-lib/esm'
// Imports only the code needed for the icon
import { question } from 'dnb-ui-lib/icons'
import { question } from 'dnb-ui-lib/esm/icons'

CommonJS (CJS)

Node.js uses RequireJS and has CommonJS as their default module format.

SSR

In case you are using the dnb-ui-lib in a classic Node.js environment, like typical in SSR, you can import or require everything from the /cjs subfolder:

// Components
import { Button } from 'dnb-ui-lib/cjs'
const { Button } = require('dnb-ui-lib/cjs/components')
const Button = require('dnb-ui-lib/cjs/components/Button')
// Icons
import { question } from 'dnb-ui-lib/cjs/icons'
const { question } = require('dnb-ui-lib/cjs/icons')
const question = require('dnb-ui-lib/cjs/icons/question')
// Styles
import 'dnb-ui-lib/cjs/style'
require('dnb-ui-lib/cjs/style')

Use ESM in Node.js anyway

You can easily use ESM in Node.js environment. Have a look at the Next.js example.

  1. Install the esm package: npm i esm -D
  2. Call Node with an environment variable: NODE_OPTIONS='-r esm' node ...
// package.json
"start": "NODE_OPTIONS='-r esm' next start ./src"

ES6

In some cases you may want to import an ES6 version.

// ES6 version of all Components
import { Button } from 'dnb-ui-lib/es'
import { Button } from 'dnb-ui-lib/es/components'
// ES6 version of a single component
import Button from 'dnb-ui-lib/es/components/Button'

Make sure your environment has a production build with:

  • Tree Shaking
  • Compile to ES5 for IE support
  • Minify and mangle the Output

By default, webpack v4 does this fine.

Tree shaking

To optimize the bundle size, we have several options. It also depends on what is used to make the bundle. Is webpack used, then you may read a good guide on Tree Shaking.

If you only need / import a few components, you may consider to import them directly, without named imports (ES5):

import MyMaskedInput from 'dnb-ui-lib/components/InputMasked'
import MyMaskedInput from 'dnb-ui-lib/cjs/components/InputMasked'
// or
import Input from 'dnb-ui-lib/components/input-masked/InputMasked'
import Input from 'dnb-ui-lib/cjs/components/input-masked/InputMasked'

... or as ES6 imports:

import { InputMasked } from 'dnb-ui-lib/es/components'