Skip to main content

Namespace vs Named Imports

––– views

What’s the difference between these two imports?

import * as React from 'react';
import { useState, useEffect } from 'react';

Does it mean by using import *, it will import all of them, even the unused one to the production?

Turns out, it won’t.

Let’s see a simpler example

Exported

We have these components exported from components.js

// src/components.js
export const A = () => 'A Component';
export const B = () => 'B Component';
export const C = () => 'C Component';

Namespace Import

Imports all of the exported variables from a file under one name.

import * as Component from './components'
 
<Component.A />
<Component.B />

Named Import

Import specific variables from a file while using the original variable name

import { A, B } from './components'
 
<A />
<B />

Tree-Shaking

Both can be tree-shaken, if we look at the production build, only ‘A Component’ and ‘B Component’ will be there, and ‘C Component’ will not shipped to production.

Namespace Import Production Build

Namespace Import Production Build

Named Import Production Build

Named Import Production Build

No difference, just use the one you like!

Reference

dev.to/mapleleaf

developer.mozilla.org