Mozilla documentations
// fileA.ts
export const a = 'a'
export const b = 'b'
// fileB.ts
import { a, b } from './fileA'
Ok. This is pretty simple. Let’s get more advanced!
// fileB.ts
import { a as betterA, b as betterB } from './fileA'
You can also export a single value or have a fallback value for your module (file)
// fileA.ts
export const a = 'a'
export default defaultExport = 'default'
// fileB.ts
import exported, { a } from './fileA' // note that when importing, the default import can be named anything
console.log(exported, a) // 'default' 'a'
To be honest, I prefer using named exports (not default). It helps you backtrack to specific exported variables/functions easier. However if you only have one value that you’re exporting, it might be better to use a default export.
We useindex.ts
as re-exporters/aggregators (interchangeable names). See the page here:
You can export imported values in one line
// folderA/fileA.ts
export const a = 'a'
export const b = 'b'
export default c = 'c'
// folderA/index.ts
export { default, a, b } from './fileA' // to re-export the default value, use the default keyword
// folderB/fileB.ts
import c, { a, b } from '../folderA'
You can re-export a default
import as a named export.
// folderA/fileA.ts
export const a = 'a'
export const b = 'b'
export default c = 'c'
// folderA/index.ts
export { default as c, a, b } from './fileA' // re-exported the default import as a named export
// folderB/fileB.ts
import { a, b, c } from '../folderA' // since the default export in fileA is a named export in index.ts, so you have to import it as a named import