Home > Blockchain >  What's the point of re-exporting * and { default } in zustand.js?
What's the point of re-exporting * and { default } in zustand.js?

Time:10-02

I am trying to read and understand the source code of zustand and encountered this code in index.ts

export * from './vanilla'
export * from './react'
export { default as createStore } from './vanilla'
export { default } from './react'

What's the point of line 3 and 4? I thought that it might be to enable importing functions in both manners, this way

import create from 'zustand'

and this way

import { create } from 'zustand'

but the second import throws the error:

Module '"zustand"' has no exported member 'create'. Did you mean to use 'import create from "zustand"' instead?

EDIT: I am aware of what I need to do to correctly import the create function. I just don't understand why the index.ts needs line 3 and 4. What are the effects of that.

CodePudding user response:

What this does:

export { default as createStore } from './vanilla'

is - it takes the default export from that file, and in this file, exports it under the name createStore.

What this does:

export { default } from './react'

is - it takes the default export from that file, and in this file, exports it as default.

Without lines 3 and 4, the above would not occur - neither default export from vanilla nor react would be re-exported here. (doing export * from only re-exports named exports)

create is not a named export in the vanilla nor react files, and neither lines 3 nor 4 create an export named create, so import { create } from 'zustand' (which tries to retrieve the export named create) isn't permitted.

When consuming zustand, to import vanilla's default export, you'd need to do

import { createStore } from 'zustand';
// this can be renamed when importing with `as` if desired

To import React's default export, you'd need to do

import create from 'zustand';
// this can be named whatever you want, since it's a default import

If lines 3 and 4 didn't exist, neither of those two above snippets would work, because the default exports from react and vanilla wouldn't be re-exported.

  • Related